Example #1
0
    def upload_attachment(self, file_path):
        __, file_name = os.path.split(file_path)
        mime = MimeTypes()
        url = urllib.pathname2url(file_path)
        mime_type, __ = mime.guess_type(url)

        data = {
            'file_name': file_name,
            'file_type': mime_type
        }
        url = urljoin(self.api_url, 'attachment/upload')
        response = self.post(url, data=data)

        with open(file_path) as fh:
            file_data = fh.read()

        upload_response = requests.put(
            response['upload_url'],
            data=file_data,
            headers={'content-type': mime_type},
            params={'file': file_path}
        )
        upload_response.raise_for_status()

        return {
            'file_url': response['file_url'],
            'file_type': mime_type,
        }
Example #2
0
def get_mime_type(path):
    mime = MimeTypes()

    mime_type = mime.guess_type(path)[0]
    if not mime_type:
        mime_type = "text/{0}".format(os.path.splitext(path)[1])
    return mime_type
Example #3
0
 def getMimeType(self,buffre,url,mtype):
     
     if '?' in url:
         url = url.split('?')[0]
         
     mime = MimeTypes()
     ext = os.path.splitext(url)[1]
     if mtype == 'text/html' and ext == '':
         if url[-1] == '/':
             l = len(url)-1
             
             url = url[0:-1]                         
         url = url+'/index.html'
         ext = '.html'
         
     #ext1 = mime.guess_extension(mtype,True)
     #print ext1
     mime_type = mime.guess_type(url)        
     #print url
     if ext:
         #print url
         u = urlparse.urlparse(url)
         #print u.netloc,u.path
         print self.host
         if self.host:
             root_dir = self.root_dir+"/"+self.host
             
         file_path = os.path.join(root_dir,u.netloc+u.path)
         print file_path
         #if not os.path.isfile(file_path):
         makeDir(os.path.dirname(file_path))
         f = open(file_path,"wb")            
         f.write(buffre)            
Example #4
0
 def update_community(self, properties):
     pc = api.portal.get_tool('portal_catalog')
     brain = pc.unrestrictedSearchResults(portal_type='ulearn.community',
                                          community_hash=self.params['community'])
     if not brain:
         brain = pc.unrestrictedSearchResults(portal_type='ulearn.community',
                                              gwuuid=self.params['community'])
     if brain:
         community = brain[0].getObject()
         if properties['title'] is not None:
             community.title = properties['title']
         if properties['description'] is not None:
             community.description = properties['description']
         if properties['image'] is not None:
             imageObj = ''
             mime = MimeTypes()
             mime_type = mime.guess_type(properties['image'])
             imgName = (properties['image'].split('/')[-1]).decode('utf-8')
             imgData = requests.get(properties['image']).content
             imageObj = NamedBlobImage(data=imgData,
                                       filename=imgName,
                                       contentType=mime_type[0])
             community.image = imageObj
         if properties['activity_view'] is not None:
             community.activity_view = properties['activity_view']
         if properties['twitter_hashtag'] is not None:
             community.twitter_hashtag = properties['twitter_hashtag']
         if properties['notify_activity_via_push'] is not None:
             community.notify_activity_via_push = True if properties['notify_activity_via_push'] == 'True' else None
         if properties['notify_activity_via_push_comments_too'] is not None:
             community.notify_activity_via_push_comments_too = True if properties['notify_activity_via_push_comments_too'] == 'True' else None
         community.reindexObject()
         return True
     else:
         return False
Example #5
0
def download(request, filename):
    #down_file = File.objects.get(name = filename)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    DOWNLOAD_URL = BASE_DIR+"/download/"
    file_path = DOWNLOAD_URL + filename
    file_name = filename
    fp = open(file_path, 'rb')
    response = HttpResponse(fp.read())
    fp.close()
    mime = MimeTypes()
    type, encoding = mime.guess_type(file_name)
    if type is None:
        type = 'application/octet-stream'
    response['Content-Type'] = type
    response['Content-Length'] = str(os.stat(file_path).st_size)
    if encoding is not None:
        response['Content-Encoding'] = encoding
    if u'WebKit' in request.META['HTTP_USER_AGENT']:
        filename_header = 'filename=%s' % file_name.encode('utf-8')
    elif u'MSIE' in request.META['HTTP_USER_AGENT']:
        filename_header = ''
    else:
        filename_header = 'filename*=UTF-8\'\'%s' % urllib.quote(file_name.encode('utf-8'))
    response['Content-Disposition'] = 'attachment; ' + filename_header
    # 記錄系統事件
    if is_event_open(request) :       
        log = Log(user_id=request.user.id, event=u'下載檔案<'+filename+'>')
        log.save()     
    return response
Example #6
0
 def mime_type(self):
     m = MimeTypes()
     m.read(LIASIS_DIR+MIME_TYPES)
     if m.guess_type(self.tfile):
         return m.guess_type(self.tfile)[0]
     else:
         return "text/plain"
def GetRFC(rfc_id,file_name,peer_ip,peer_port):
    global LRFCdata
    global Server
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(None)
    peer_ipaddr=peer_ip
    s.connect((peer_ipaddr,int(peer_port)))
    
    message = ["GETRFC",str(rfc_id),"P2P-DI/1.0","Host: ",IP,"Port: ",PORT,"Title: ",file_name,"Client ID: ",str(self_id)]
    s.send(pickle.dumps(message))

    os.chdir(os.getcwd())
    filename=file_name+".pdf"
    file1=open(filename,'wb')
    
    q=s.recv(4096)
    q=pickle.loads(q)
    
    if 'FILE NOT FOUND' in q:
        code = '404'
        phrase = 'FILE NOT FOUND'
        reply = ["P2P-DI/1.0 ",str(code),str(phrase)]
        PrintResponse(reply,'FILERESPN')
    else:
        if 'FILE FOUND' in q:
            last_modified = q[2]
            message = ["OK"]
            s.send(pickle.dumps(message))
            while True:
                q=s.recv(4096)
                if q:
                    file1.write(q)
                else:
                    code = '200'
                    phrase = 'OK'
                    mime = MimeTypes()
                    filesize = os.stat(filename).st_size
                    mime_type = mime.guess_type(filename)
                    reply = ["P2P-DI/1.0 ",str(code),str(phrase),"Last-Modified: ",str(last_modified),"Content-Length: ",str(filesize),"Content-Type: ",str(mime_type[0])]
                    PrintResponse(reply,'FILESENT')
                    file1.close()
                    break

            serverIP = Server[0]
            serverPort = Server[1]
            message=["PQUERY","P2P-DI/1.0 ",str(self_id),"Host: ",IP,"Port: ",str(PORT)]
            reply = client(message,serverIP,serverPort)
            PrintResponse(reply,'PQUERY')
            

            LocalRFC = LocalRFCRecord(rfc_id,file_name)
            LRFCdata.append(LocalRFC.getLocalRFC())
            Local_linked_list.append(LocalRFC.getLocalRFC())

            active_list = reply[4]    
            active_list=RFCStore(active_list,[[rfc_id,file_name]])
    
    s.close()
Example #8
0
    def export_warc(self):
        # by using select_for_update and checking for existence of this file,
        # we make sure that we won't accidentally try to create the file multiple
        # times in parallel.
        asset = self.assets.select_for_update().first()
        if not asset:
            return  # this is not an old-style Link
        if default_storage.exists(self.warc_storage_file()):
            return

        guid = self.guid
        out = self.open_warc_for_writing()

        def write_resource_record(file_path, url, content_type):
            self.write_warc_resource_record(
                default_storage.open(file_path),
                url.encode('utf8'),
                content_type,
                default_storage.created_time(file_path),
                out)

        def write_metadata_record(metadata, target_headers):
            concurrent_to = (v for k, v in target_headers if k == warctools.WarcRecord.ID).next()
            warc_date = (v for k, v in target_headers if k == warctools.WarcRecord.DATE).next()
            url = (v for k, v in target_headers if k == warctools.WarcRecord.URL).next()
            self.write_warc_metadata_record(metadata, url, concurrent_to, warc_date, out)

        # write PDF capture
        if asset.pdf_capture and ('cap' in asset.pdf_capture or 'upload' in asset.pdf_capture):
            file_path = os.path.join(asset.base_storage_path, asset.pdf_capture)
            headers = write_resource_record(file_path, "file:///%s/%s" % (guid, asset.pdf_capture), 'application/pdf')
            #write_metadata_record({'role':'primary', 'user_upload':asset.user_upload}, headers)

        # write image capture (if it's not a PDF thumbnail)
        elif (asset.image_capture and ('cap' in asset.image_capture or 'upload' in asset.image_capture)):
            file_path = os.path.join(asset.base_storage_path, asset.image_capture)
            mime_type = get_mime_type(asset.image_capture)
            write_resource_record(file_path, "file:///%s/%s" % (guid, asset.image_capture), mime_type)

        if asset.warc_capture:
            # write WARC capture
            if asset.warc_capture == 'archive.warc.gz':
                file_path = os.path.join(asset.base_storage_path, asset.warc_capture)
                self.write_warc_raw_data(default_storage.open(file_path), out)

            # write wget capture
            elif asset.warc_capture == 'source/index.html':
                mime = MimeTypes()
                for root, dirs, files in default_storage.walk(os.path.join(asset.base_storage_path, 'source')):
                    rel_path = root.split(asset.base_storage_path, 1)[-1]
                    for file_name in files:
                        mime_type = mime.guess_type(file_name)[0]
                        write_resource_record(os.path.join(root, file_name),
                                              "file:///%s%s/%s" % (guid, rel_path, file_name), mime_type)

        self.close_warc_after_writing(out)

        # regenerate CDX index
        self.cdx_lines.all().delete()
Example #9
0
def searchImages(rootDir):
    imageList = []
    mime = MimeTypes()
    for root, subFolders, files in os.walk(rootDir):
        for file in files:
            mt = mime.guess_type(file)[0]
            if mt and mt.startswith('image/'):
                imageList = imageList + [os.path.join(root,file)]
    return imageList
Example #10
0
def configure_mimetypes(extra_types):
    """
    Add additional mimetypes to a local MimeTypes instance to avoid polluting
    global registery
    """
    mimetypes = MimeTypes()
    for content_type, extension in extra_types:
        mimetypes.add_type(content_type, extension)
    return mimetypes
Example #11
0
def get_extension(url):
    from mimetypes import MimeTypes
    mime_types = MimeTypes()

    (type, encoding) = mime_types.guess_type(url)
    extensions = mime_types.guess_all_extensions(type)
    extension = extensions[-1]

    return extension
Example #12
0
def add_documents(request, category_id):
    if request.is_ajax():
        files = request.GET.getlist('files', False)
        cat = Category.objects.get(id=category_id)
        l_doc = []
        l_pdf = []
        cmds = []
        paths = []
        for f in list(files):
            mime = MimeTypes()
            path = os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_DIR, f)
            m = mime.guess_type(path)[0]
            d = Document(name=f.encode('ascii', 'ignore'), owner=request.user, refer_category=cat)
            d.save()
            cat.add_doc(d)
            if m == 'application/pdf':
                l_pdf.append(([cat], path, f, [d]))
            elif m in ['image/png', 'image/jpeg', 'image/bmp']:
                im = Image.open(path)
                w, h = im.size
                new_filename = str(d.id) + '_' + f
                new_path = os.path.join(cat.get_absolute_path(), new_filename)
                shutil.copy2(path, new_path)
                d.add_page(d.get_npages() + 1, new_filename, w, h)
                for fu in FileUpload.objects.all():
                    if fu.file.path == path:
                        fu.delete()
                d.complete = True
                d.save()
                remove_fileupload([path])
            elif m in ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']:
                p = re.compile(r'.[Dd][Oo][Cc][xX]?$')
                new_f = p.sub('.pdf', f)
                new_path = path.replace(f, new_f)
                cmd = 'soffice --headless --convert-to pdf  %s --outdir %s/upload' % (path, settings.MEDIA_ROOT)
                cmds.append(cmd)
                paths.append(path)
                l_doc.append(([cat], new_path, new_f, [d]))
            elif m in ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']:
                p = re.compile(r'.[Xx][Ll][Ss][xX]?$')
                new_f = p.sub('.pdf', f)
                new_path = path.replace(f, new_f)
                cmd = 'soffice --headless --convert-to pdf  %s --outdir %s/upload' % (path, settings.MEDIA_ROOT)
                cmds.append(cmd)
                paths.append(path)
                l_doc.append(([cat], new_path, new_f, [d]))
            else:
                print 'ERREUR FORMAT FICHIER'
        if len(l_doc):
            thread1 = Timer(0, manage_convert_doc_to_pdf, (cmds, paths, l_doc,))
            thread1.start()
        if len(l_pdf):
            thread = Timer(0, manage_convert_pdf_to_jpg, (l_pdf,))
            thread.start()
        results = {'doc_list': [d.as_json() for d in cat.get_docs()], 'n': cat.count_docs()}
        return HttpResponse(json.dumps(results))
Example #13
0
 def mime(self):
     if self.mMimeType is not None:
         return self.mMimeType
     
     mime = MimeTypes()
     url = urllib.pathname2url(self.mFullPathName)
     self.mMimeType = mime.guess_type(url)[0]
     if self.mMimeType is None:
         self.mMimeType = "Unkown/None"
     return self.mMimeType
Example #14
0
File: pyle.py Project: hrkfdn/pyle
def showfile(file):
    mime = MimeTypes()
    mime_type = mime.guess_type(file)
    if mime_type[0] is not None and mime_type[0].startswith("image"):
        return render_template("image.html",
                title="pyle :: preview",
                filepath="/data/" + file,
                filename=os.path.basename(file))
    else:
        return readfile(file)
Example #15
0
 def show_media(self, url, title = "", desc ="", loop = 0):
     mime = MimeTypes()
     mime_type = mime.guess_type(url)
     payload = {
         "target": url,
         "title":title,
         "description":desc,
         "mimeType": mime_type[0],
         "iconSrc":"",
         "loop":loop}
     command = '{"id":"images","type":"request","uri":"ssap://media.viewer/open","payload":'+ json.dumps(payload)+'}'
     self.send_command(command)
Example #16
0
    def transform_import_values(self, value):
        '''
        # TODO: Following commented code can be used if user does not already have file in final location using django ORM:

        request = HttpRequest()
        # request.FILES['file-list_' + str(nodeid)] = None
        files = []
        # request_list = []

        for val in value.split(','):
            val_dict = {}
            val_dict['content'] = val
            val_dict['name'] = val.split('/')[-1].split('.')[0]
            val_dict['url'] = None
            # val_dict['size'] = None
            # val_dict['width'] = None
            # val_dict['height'] = None
            files.append(val_dict)
            f = open(val, 'rb')
            django_file = InMemoryUploadedFile(f,'file',val.split('/')[-1].split('.')[0],None,None,None)
            request.FILES.appendlist('file-list_' + str(nodeid), django_file)
        print request.FILES
        value = files
        '''

        mime = MimeTypes()
        tile_data = []
        for file_path in value.split(','):
            try:
                file_stats = os.stat(file_path)
                tile_file['lastModified'] = file_stats.st_mtime
                tile_file['size'] =  file_stats.st_size
            except:
                pass
            tile_file = {}
            tile_file['file_id'] =  str(uuid.uuid4())
            tile_file['status'] = ""
            tile_file['name'] =  file_path.split('/')[-1]
            tile_file['url'] =  settings.MEDIA_URL + 'uploadedfiles/' + str(tile_file['name'])
            # tile_file['index'] =  0
            # tile_file['height'] =  960
            # tile_file['content'] =  None
            # tile_file['width'] =  1280
            # tile_file['accepted'] =  True
            tile_file['type'] =  mime.guess_type(file_path)[0]
            tile_file['type'] = '' if tile_file['type'] == None else tile_file['type']
            tile_data.append(tile_file)
            file_path = 'uploadedfiles/' + str(tile_file['name'])
            fileid = tile_file['file_id']
            models.File.objects.get_or_create(fileid=fileid, path=file_path)

        result = json.loads(json.dumps(tile_data))
        return result
    def get_mime_type(self, file_path):
        #Get mime type
        try:
            mime = MimeTypes()
            murl = urllib.pathname2url(file_path)
            mime_type = mime.guess_type(murl)[0]
            if mime_type == None:
                mime_type = 'text/plain'
        except:
            mime_type = 'text/plain'

        return mime_type
Example #18
0
	def addFileOutput(self, name, filepath):
		data = open(filepath).read()
		filename = os.path.basename(filepath)
		mime = MimeTypes()
		mime_guess = mime.guess_type(filename)[0]

		self.result[name] = {
			"filename": filename,
			"content-type": mime_guess,
			"data": base64.b64encode(data)
		}
		return self
    def update_data(self, data, content_type, size):
        """

        """
        if not data:
            # still index
            self.index_object()
            return

        passed, virus_name = DataVirusCheckAdapter(data).process()

        if not passed:
            log.warn('found virus %s, rejecting file' % virus_name)
            raise XWFFileError('found virus %s, rejecting file' % virus_name)

        # this isn't necessarily an error, on init we get called without data
        base_files_dir = self._base_files_dir
        self.size = size
        self.set_modificationTime()

        if base_files_dir:
            fileId = os.path.join(base_files_dir, self.getId())
            f = file(fileId, 'wb+')

            if hasattr(data, '__class__') and data.__class__ is Pdata:
                while data is not None:
                    f.write(data.data)
                    data = data.next
            else:
                f.write(data)

            f.close()

        # fix the title
        title = to_unicode_or_bust(self.title)
        title = removePathsFromFilenames(title)
        self.title = title

        if content_type is not None:
            self.content_type = content_type
        else:
            mtypes = MimeTypes()
            mime_type = mtypes.guess_type(title)
            if mime_type:
                self.content_type = mime_type

        self.ZCacheable_invalidate()
        self.ZCacheable_set(None)
        self.http__refreshEtag()

        # index ourselves into the catalog
        self.index_object()
Example #20
0
def get_base64_image(url):
    template_image = ''
    mime = MimeTypes()
    mime_type = mime.guess_type(url)[0]
    # Steam the image from the url
    request = requests.get(url)
    image_buffer = StringIO(request.content)

    if image_buffer:
        template_image = image_buffer.getvalue().encode('base64')
        template_image = u'data:%s;base64,%s' % (mime_type, template_image)

    return template_image
    def batch_upload_response(self, request):
        output_fields = flatten_fieldsets(self.fieldsets)
        
        media_file_name = get_media_file_name(self, self.model)


        #Disabling exception handling here @olivierdalang's feedback:
        # try:
        latest_log_entry = LogEntry.objects.filter(action_flag=ADDITION).order_by('-action_time')[0]
        ct = ContentType.objects.get_for_id(latest_log_entry.content_type_id)
        obj = ct.get_object_for_this_type(pk=latest_log_entry.object_id)
        
        if obj:

            object_data = {}

            mime = MimeTypes()
            media_file = get_media_file(self, self.model, obj)
            media_file_url = media_file.url #urllib.pathname2url(media_file.url) #Not sure why i had this, but it's escaping the URL
            
            mime_type = mime.guess_type(media_file_url)
            edit_url = reverse('admin:%s_%s_change' %(obj._meta.app_label,  obj._meta.model_name),  args=[obj.id] )

            object_data['media_file_url'] = media_file_url
            object_data['media_file_size'] = media_file.size
            object_data['media_file_type'] = mime_type[0]
            object_data['edit_url'] = mark_safe(edit_url)

            field_values = {}

            for output_field in output_fields:
                value = str(self.get_field_contents(output_field, obj))
                label = str(label_for_field(output_field, self.model, self))

                field_values[output_field] = {
                    'label':label,
                    'value':value
                }

            object_data['field_values'] = field_values
            

            data = {
                "success":True,
                "files":[
                    object_data
                ]
            }
            json_dumped = json.dumps(data)

            return HttpResponse(json_dumped, content_type='application/json')
Example #22
0
def filetype(file):
 name= ''
 mime = MimeTypes()
 mime_type = mime.guess_type(file)
 #print(mime_type)


 if "application/x-zip-compressed" in mime_type:
  name= "zip"
 elif "gzip" in mime_type:
  name= "gzip"
 elif "application/x-tar" in mime_type:  
  name= "tar"
 return name
Example #23
0
    def upload(self, filepath):
        filename = filepath.split("/")[-1]
        mime = MimeTypes()
        mime_type = mime.guess_type(filename)
        data = {"filename": filename, "mime_type": mime_type}
        response = self.session.post("%s/files/" % self.url, data=json.dumps(data), headers=HEADERS)

        if response.status_code == requests.codes.created:
            f = File(self, response.json())
            with open(filepath, "rb") as localfile:
                response = requests.put(f.upload_url, data=localfile)
                return f
        else:
            print(response.text)
Example #24
0
    def mimes(self):
        """
        Returns extended MimeTypes.
        """
        _mimes = MimeTypes(strict=False)
        _mimes.suffix_map.update({".tbz2": ".tar.bz2"})
        _mimes.encodings_map.update({".bz2": "bzip2"})

        if cfg["CFG_BIBDOCFILE_ADDITIONAL_KNOWN_MIMETYPES"]:
            for key, value in iteritems(cfg["CFG_BIBDOCFILE_ADDITIONAL_KNOWN_MIMETYPES"]):
                _mimes.add_type(key, value)
                del key, value

        return _mimes
Example #25
0
 def write(self, filename, contents, encoding='utf8'):
     """
     Write a file to the data store.
     """
     mime = MimeTypes()
     mime.add_type('text/x-yaml', '.yaml')
     content_type, _ = mime.guess_type(filename)
     key = self.bucket.new_key(self._path(filename))
     key.set_contents_from_string(contents.encode(encoding), {
         'Content-Type': content_type or 'text/plain',
         'Content-Encoding': encoding,
     })
     if self.public:
         key.set_canned_acl('public-read')
Example #26
0
def _getExtension( episode ):
	# get extension from url
	urlExt = os.path.splitext( episode.url )[ 1 ]
	# get extension from media type
	mime = MimeTypes()
	mimeExtList = mime.guess_all_extensions( episode.type )
	# check if url extension matches any item in list
	if urlExt in mimeExtList:
		# yep, then url extension is good
		return urlExt
	# otherwise, use recommendation from MimeTypes, as default we use .mp3  	
	mimeExt = mime.guess_extension( episode.type )
	if mimeExt == None:
		mimeExt = ".mp3"
	return mimeExt
Example #27
0
def Email(subject, body, path=0):
    

    msg = Message(subject,
        sender="*****@*****.**",
        recipients=["*****@*****.**"])
    msg.body = body
    if path!=0:
        mim=MimeTypes()
        for fn in os.listdir(path):
            mimty=mim.guess_type(fn)
            with app.open_resource(path+"\\"+fn) as fp:
                msg.attach(fn,mimty[0], fp.read())
        shutil.rmtree(path)
    mail.send(msg)
Example #28
0
    def POST(self):
        params = {}
        params['nom'] = self.params.pop('title')
        params['community_type'] = self.params.pop('community_type')
        params['description'] = self.params.pop('description', None)
        params['image'] = self.params.pop('image', None)
        params['activity_view'] = self.params.pop('activity_view', None)
        params['twitter_hashtag'] = self.params.pop('twitter_hashtag', None)
        params['notify_activity_via_push'] = self.params.pop('notify_activity_via_push', None)
        params['notify_activity_via_push_comments_too'] = self.params.pop('notify_activity_via_push_comments_too', None)

        pc = api.portal.get_tool('portal_catalog')
        nom = safe_unicode(params['nom'])
        util = queryUtility(IIDNormalizer)
        id_normalized = util.normalize(nom, max_length=500)
        result = pc.unrestrictedSearchResults(portal_type='ulearn.community',
                                              id=id_normalized)

        imageObj = ''
        if params['image']:
            mime = MimeTypes()
            mime_type = mime.guess_type(params['image'])
            imgName = (params['image'].split('/')[-1]).decode('utf-8')
            imgData = requests.get(params['image']).content
            imageObj = NamedBlobImage(data=imgData,
                                      filename=imgName,
                                      contentType=mime_type[0])

        if result:
            # community = result[0].getObject()
            success_response = 'Community already exists.'
            status = 200
        else:
            new_community_id = self.context.invokeFactory('ulearn.community', id_normalized,
                                                          title=params['nom'],
                                                          description=params['description'],
                                                          image=imageObj,
                                                          community_type=params['community_type'],
                                                          activity_view=params['activity_view'],
                                                          twitter_hashtag=params['twitter_hashtag'],
                                                          notify_activity_via_push=True if params['notify_activity_via_push'] == 'True' else None,
                                                          notify_activity_via_push_comments_too=True if params['notify_activity_via_push_comments_too'] == 'True' else None,
                                                          checkConstraints=False)
            new_community = self.context[new_community_id]
            success_response = 'Created community "{}" with hash "{}".'.format(new_community.absolute_url(), sha1(new_community.absolute_url()).hexdigest())
            status = 201
        logger.info(success_response)
        return ApiResponse.from_string(success_response, code=status)
Example #29
0
 def __init__(self):
     self.classes = {}
     self.mimetypes = MimeTypes()
     mimedata = get_data('scrapy', 'mime.types')
     self.mimetypes.readfp(StringIO(mimedata))
     for mimetype, cls in self.CLASSES.iteritems():
         self.classes[mimetype] = load_object(cls)
Example #30
0
    def post_media(self, user_id, file_path, sent_by_maker=False):
        role = "appUser"
        if sent_by_maker:
            role = "appMaker"

        data = {"role": role}

        mime = MimeTypes()
        mime_type, _ = mime.guess_type(file_path)

        file_name = os.path.basename(file_path)
        files = {'source': (file_name, open(file_path, 'rb'), mime_type)}

        url = 'appusers/{0}/conversation/images'.format(user_id)

        return self.ask(url, data, 'post', files)
Example #31
0
def run_campaign(campaign, domain='demo.django-crm.io', protocol='https'):
    try:
        campaign = Campaign.objects.get(id=campaign)
        attachments = []
        if campaign.attachment:
            file_path = campaign.attachment.path
            file_name = file_path.split("/")[-1]
            content = open(file_path, 'rb').read()
            mime = MimeTypes()
            mime_type = mime.guess_type(file_path)
            attachments.append((file_name, content, mime_type[0]))
        subject = campaign.subject

        contacts = Contact.objects.filter(contact_list__in=[
            each_list for each_list in campaign.contact_lists.all()
        ])
        default_html = campaign.html_processed
        for each_contact in contacts:
            html = default_html
            campaign_log = CampaignLog.objects.create(contact=each_contact,
                                                      campaign=campaign)
            if campaign.reply_to_email:
                reply_to_email = campaign.reply_to_email
            else:
                message_id = get_campaign_message_id(campaign_log)
                campaign_log.message_id = message_id
                campaign_log.save()
                domain_name = 'django-crm.com'
                if campaign.from_email is not None:
                    from_email = campaign.from_email
                else:
                    from_email = campaign.created_by.email
                reply_to_email = str(from_email) + ' <' + \
                    str(message_id + '@' + domain_name + '') + '>'
            if not (each_contact.is_bounced or each_contact.is_unsubscribed):
                # domain_url = settings.URL_FOR_LINKS
                domain_url = protocol + '://' + domain
                img_src_url = domain_url + reverse(
                    'marketing:campaign_open',
                    kwargs={
                        'campaign_log_id': campaign_log.id,
                        'email_id': each_contact.id
                    })
                # images can only be accessed over https
                link = '<img src={img_src_url} alt="company_logo" title="company_logo" height="1" width="1" />'.format(
                    img_src_url=img_src_url)
                # link = '<img src="' + domain_url + '/m/cm/track-email/' + \
                #     str(campaign_log.id) + '/contact/' + \
                #     str(each_contact.id) + '/" height="1" width="1" alt="company_logo" + \
                #     title="company_logo"/>'

                unsubscribe_from_campaign_url = reverse(
                    'marketing:unsubscribe_from_campaign',
                    kwargs={
                        'contact_id': each_contact.id,
                        'campaign_id': campaign.id
                    })
                unsubscribe_from_campaign_html = "<br><br/><a href={}>Unsubscribe</a>".format(
                    domain_url + unsubscribe_from_campaign_url)
                names_dict = {
                    'company_name':
                    each_contact.company_name
                    if each_contact.company_name else '',
                    'last_name':
                    each_contact.last_name if each_contact.last_name else '',
                    'city':
                    each_contact.city if each_contact.city else '',
                    'state':
                    each_contact.state if each_contact.state else '',
                    'first_name':
                    each_contact.name,
                    'email':
                    each_contact.email,
                    'email_id':
                    each_contact.id,
                    'name':
                    each_contact.name + ' ' +
                    each_contact.last_name if each_contact.last_name else '',
                    'unsubscribe_from_campaign_url':
                    unsubscribe_from_campaign_url
                }

                html = Template(html).render(Context(names_dict))
                mail_html = html + link + unsubscribe_from_campaign_html
                from_email = str(campaign.from_name) + "<" + \
                    str(campaign.from_email) + '>'
                to_email = [each_contact.email]
                send_campaign_mail(subject, mail_html, from_email, to_email,
                                   [], [reply_to_email], attachments)
    except Exception as e:
        print(e)
        pass
Example #32
0
    def run(self, path):
        if path == "/":
            f = open(os.path.join(config.get_runtime_path(), "platformcode", "template", "page.html"), "rb")
            self.handler.send_response(200)
            self.handler.send_header('Content-type', 'text/html')
            self.handler.end_headers()
            respuesta = f.read()
            self.handler.wfile.write(respuesta)
            f.close()

        elif path.startswith("/local/"):
            import base64
            import urllib
            Path = path.replace("/local/", "").split("/")[0]
            Path = base64.b64decode(urllib.unquote_plus(Path))
            Size = int(os.path.getsize(Path.decode("utf8")))
            f = open(Path.decode("utf8"), "rb")
            if not self.handler.headers.get("range") == None:
                if "=" in str(self.handler.headers.get("range")) and "-" in str(self.handler.headers.get("range")):
                    Inicio = int(self.handler.headers.get("range").split("=")[1].split("-")[0])
                    if self.handler.headers.get("range").split("=")[1].split("-")[1] <> "":
                        Fin = int(self.handler.headers.get("range").split("=")[1].split("-")[1])
                    else:
                        Fin = Size - 1

            else:
                Inicio = 0
                Fin = Size - 1

            if not Fin > Inicio: Fin = Size - 1

            if self.handler.headers.get("range") == None:
                logger.info("-------------------------------------------------------")
                logger.info("Solicitando archivo local: " + Path)
                logger.info("-------------------------------------------------------")

                self.handler.send_response(200)
                self.handler.send_header("Content-Disposition", "attachment; filename=video.mp4")
                self.handler.send_header('Accept-Ranges', 'bytes')
                self.handler.send_header('Content-Length', str(Size))
                self.handler.send_header("Connection", "close")
                self.handler.end_headers()
                while True:
                    time.sleep(0.2)
                    buffer = f.read(1024 * 250)
                    if not buffer:
                        break
                    self.handler.wfile.write(buffer)
                self.handler.wfile.close()
                f.close()
            else:
                logger.info("-------------------------------------------------------")
                logger.info("Solicitando archivo local: " + Path)
                logger.info("Rango: " + str(Inicio) + "-" + str(Fin) + "/" + str(Size))
                logger.info("-------------------------------------------------------")
                f.seek(Inicio)

                self.handler.send_response(206)
                self.handler.send_header("Content-Disposition", "attachment; filename=video.mp4")
                self.handler.send_header('Accept-Ranges', 'bytes')
                self.handler.send_header('Content-Length', str(Fin - Inicio))
                self.handler.send_header('Content-Range', str(Inicio) + "-" + str(Fin) + "/" + str(Size))
                self.handler.send_header("Connection", "close")

                self.handler.end_headers()
                while True:
                    time.sleep(0.2)
                    buffer = f.read(1024 * 250)
                    if not buffer:
                        break
                    self.handler.wfile.write(buffer)
                self.handler.wfile.close()
                f.close()
        elif path.startswith("/media/"):
            file = os.path.join(config.get_runtime_path(), "platformcode", "template", path[7:])
            from mimetypes import MimeTypes
            mime = MimeTypes()
            mime_type = mime.guess_type(file)
            try:
                mim = mime_type[0]
            except:
                mim = ""
            f = open(file, "rb")
            self.handler.send_response(200)
            self.handler.send_header('Content-type', mim)
            self.handler.end_headers()
            self.handler.wfile.write(f.read())
            f.close()
Example #33
0
content = content.replace("font-size",
                          "nope").replace("size=\"", "sizeIs=\"").replace(
                              "color=\"", "coolor=\"")

# put head code right after the head tag
content = re.sub("<head(.*>)", "<head \\1" + head_html, content, re.I | re.M)

# put upper body code right after the body tag
content = re.sub("<body(.*>)", "<body \\1" + upper_html, content, re.I | re.M)

# put lower body code right before the closing of body tag
content = re.sub("</body(.*>)", lower_html + "</body \\1", content,
                 re.I | re.M)

# base64 include all external files
mime = MimeTypes()
while True:
    result = re.search('(<img)(.*src=")(.*?)(".*?>)', content, re.I | re.M)
    if result is None or result.groups()[2].endswith('base64-ed '):
        break

    external_file = join(temp_dir, basename(unquote(result.groups()[2])))
    if not isfile(external_file):
        pass

    file_url = pathname2url(external_file)
    mime_type = mime.guess_type(file_url)[0]
    if mime_type is None:
        mime_type = 'unknown/unknown'
        print('WRONG MIME', mime.guess_type(file_url), file_url, external_file)
    b64_data = "data:" + mime_type + ";base64,"
Example #34
0
def send_campaign_email_to_admin_contact(campaign,
                                         domain='demo.django-crm.io',
                                         protocol='https'):
    try:
        campaign = Campaign.objects.get(id=campaign)
        attachments = []
        if campaign.attachment:
            file_path = campaign.attachment.path
            file_name = file_path.split("/")[-1]
            content = open(file_path, 'rb').read()
            mime = MimeTypes()
            mime_type = mime.guess_type(file_path)
            attachments.append((file_name, content, mime_type[0]))
        subject = campaign.subject
        contacts = ContactEmailCampaign.objects.all()
        default_html = campaign.html_processed
        for each_contact in contacts:
            html = default_html
            if campaign.reply_to_email:
                reply_to_email = campaign.reply_to_email
            else:
                domain_name = 'django-crm.com'
                if campaign.from_email is not None:
                    from_email = campaign.from_email
                else:
                    from_email = campaign.created_by.email
                reply_to_email = str(from_email) + ' <' + \
                    str(settings.EMAIL_HOST_USER + '@' + domain_name + '') + '>'

            # domain_url = settings.URL_FOR_LINKS
            domain_url = protocol + '://' + domain
            # img_src_url = domain_url + reverse('marketing:campaign_open', kwargs={
            #     'campaign_log_id': campaign_log.id, 'email_id': each_contact.id})
            # # images can only be accessed over https
            # link = '<img src={img_src_url} alt="company_logo" title="company_logo" height="1" width="1" />'.format(
            #     img_src_url=img_src_url)
            # link = '<img src="' + domain_url + '/m/cm/track-email/' + \
            #     str(campaign_log.id) + '/contact/' + \
            #     str(each_contact.id) + '/" height="1" width="1" alt="company_logo" + \
            #     title="company_logo"/>'

            # unsubscribe_from_campaign_url = reverse(
            #     'marketing:unsubscribe_from_campaign', kwargs={'contact_id': each_contact.id,
            #                                                     'campaign_id': campaign.id})
            # unsubscribe_from_campaign_html = "<br><br/><a href={}>Unsubscribe</a>".format(
            #     domain_url + unsubscribe_from_campaign_url)

            # names_dict = {'company_name': '', 'city': '', 'state': '',
            #                 'last_name': each_contact.last_name if each_contact.last_name else '',
            #                 'email': each_contact.email, 'email_id': each_contact.id,
            #                 'name': each_contact.name + ' ' + each_contact.last_name if each_contact.last_name else '',
            #             }

            # mail_html = html + link + unsubscribe_from_campaign_html
            html = Template(html).render(Context({'email_id':
                                                  each_contact.id}))
            mail_html = html
            from_email = str(campaign.from_name) + "<" + \
                str(campaign.from_email) + '>'
            to_email = [each_contact.email]
            send_campaign_mail(subject, mail_html, from_email, to_email, [],
                               [reply_to_email], attachments)
    except Exception as e:
        print(e)
        pass