1+ import json
2+ import logging
13import os
24from datetime import datetime
5+ from urllib .error import HTTPError , URLError
6+ from urllib .parse import urlencode
7+ from urllib .request import Request , urlopen
38
9+ # from django.conf import settings
10+ from django .core .exceptions import ValidationError
11+ from django .core .validators import URLValidator
412from django .http import JsonResponse
513from django .utils .decorators import method_decorator
614from django .views import View
1018 IMAGE_UPLOAD_PATH_DATE )
1119from .utils import storage
1220
21+ LOGGER = logging .getLogger ('django_editorjs_fields' )
22+
1323
1424class ImageUploadView (View ):
1525 http_method_names = ["post" ]
26+ # http_method_names = ["post", "delete"]
1627
1728 @method_decorator (csrf_exempt )
1829 def dispatch (self , request , * args , ** kwargs ):
@@ -35,9 +46,6 @@ def post(self, request):
3546 {'success' : 0 , 'message' : 'You can only upload images.' }
3647 )
3748
38- # filesize = len(the_file['content'])
39- # filetype = the_file['content-type']
40-
4149 filename , extension = os .path .splitext (the_file .name )
4250
4351 if IMAGE_NAME_ORIGINAL is False :
@@ -57,3 +65,82 @@ def post(self, request):
5765
5866 return JsonResponse ({'success' : 1 , 'file' : {"url" : link }})
5967 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