1
+ import json
2
+ import logging
1
3
import os
2
4
from datetime import datetime
5
+ from urllib .error import HTTPError , URLError
6
+ from urllib .parse import urlencode
7
+ from urllib .request import Request , urlopen
3
8
9
+ # from django.conf import settings
10
+ from django .core .exceptions import ValidationError
11
+ from django .core .validators import URLValidator
4
12
from django .http import JsonResponse
5
13
from django .utils .decorators import method_decorator
6
14
from django .views import View
10
18
IMAGE_UPLOAD_PATH_DATE )
11
19
from .utils import storage
12
20
21
+ LOGGER = logging .getLogger ('django_editorjs_fields' )
22
+
13
23
14
24
class ImageUploadView (View ):
15
25
http_method_names = ["post" ]
26
+ # http_method_names = ["post", "delete"]
16
27
17
28
@method_decorator (csrf_exempt )
18
29
def dispatch (self , request , * args , ** kwargs ):
@@ -35,9 +46,6 @@ def post(self, request):
35
46
{'success' : 0 , 'message' : 'You can only upload images.' }
36
47
)
37
48
38
- # filesize = len(the_file['content'])
39
- # filetype = the_file['content-type']
40
-
41
49
filename , extension = os .path .splitext (the_file .name )
42
50
43
51
if IMAGE_NAME_ORIGINAL is False :
@@ -57,3 +65,82 @@ def post(self, request):
57
65
58
66
return JsonResponse ({'success' : 1 , 'file' : {"url" : link }})
59
67
return JsonResponse ({'success' : 0 })
68
+
69
+ # def delete(self, request):
70
+ # path_file = request.GET.get('pathFile')
71
+
72
+ # if not path_file:
73
+ # return JsonResponse({'success': 0, 'message': 'Parameter "pathFile" Not Found'})
74
+
75
+ # base_dir = getattr(settings, "BASE_DIR", '')
76
+ # path_file = f'{base_dir}{path_file}'
77
+
78
+ # if not os.path.isfile(path_file):
79
+ # return JsonResponse({'success': 0, 'message': 'File Not Found'})
80
+
81
+ # os.remove(path_file)
82
+
83
+ # return JsonResponse({'success': 1})
84
+
85
+
86
+ class LinkToolView (View ):
87
+ http_method_names = ["get" ]
88
+
89
+ @method_decorator (csrf_exempt )
90
+ def dispatch (self , request , * args , ** kwargs ):
91
+ return super ().dispatch (request , * args , ** kwargs )
92
+
93
+ def get (self , request ):
94
+
95
+ url = request .GET .get ('url' , '' )
96
+
97
+ LOGGER .debug ('Starting to get meta for: %s' , url )
98
+
99
+ if not any ([url .startswith (s ) for s in ('http://' , 'https://' )]):
100
+ LOGGER .debug ('Adding the http protocol to the link: %s' , url )
101
+ url = 'http://' + url
102
+
103
+ validate = URLValidator (schemes = ['http' , 'https' ])
104
+
105
+ try :
106
+ validate (url )
107
+ except ValidationError as e :
108
+ LOGGER .error (e )
109
+ else :
110
+ try :
111
+ LOGGER .debug ('Let\' s try to get meta from: %s' , url )
112
+
113
+ full_url = 'https://api.microlink.io/?' + \
114
+ urlencode ({'url' : url })
115
+
116
+ req = Request (full_url , headers = {
117
+ 'User-Agent' : request .META .get ('HTTP_USER_AGENT' , 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' )
118
+ })
119
+ res = urlopen (req )
120
+ except HTTPError as e :
121
+ LOGGER .error ('The server couldn\' t fulfill the request.' )
122
+ LOGGER .error ('Error code: %s %s' , e .code , e .msg )
123
+ except URLError as e :
124
+ LOGGER .error ('We failed to reach a server. url: %s' , url )
125
+ LOGGER .error ('Reason: %s' , e .reason )
126
+ else :
127
+ res_body = res .read ()
128
+ res_json = json .loads (res_body .decode ("utf-8" ))
129
+
130
+ if 'success' in res_json .get ('status' ):
131
+ data = res_json .get ('data' )
132
+
133
+ if data :
134
+ LOGGER .debug ('Response meta: %s' , data )
135
+ meta = {}
136
+ meta ['title' ] = data .get ('title' )
137
+ meta ['description' ] = data .get ('description' )
138
+ meta ['image' ] = data .get ('image' )
139
+
140
+ return JsonResponse ({
141
+ 'success' : 1 ,
142
+ 'link' : data .get ('url' , url ),
143
+ 'meta' : meta
144
+ })
145
+
146
+ return JsonResponse ({'success' : 0 })
0 commit comments