Пример #1
0
def delete_personal_res(request, asset_id):
    """
        删除个人资源,直接删除文件和表,不保存
    """
    try: auth_asset = AuthAsset.objects.get(id=asset_id)
    except(AuthAsset.DoesNotExist): return FailResponse(u'资源ID(%s)不存在' % asset_id)
    
    if auth_asset.user_id <> request.user.id: return FailResponse(u'只能删除自己的资源')
    
    if auth_asset.ref_times > 0: return FailResponse(u'资源有(%s)个相关引用,不能删除' % auth_asset.ref_times)
    if auth_asset.share_times > 0: return FailResponse(u'资源有(%s)个分享,不能删除' % auth_asset.ref_times)
    
    if auth_asset.res_type == 1:
        res_type = "image"
    elif auth_asset.res_type == 2:
        res_type = "sound"
    elif auth_asset.res_type == 3:
        res_type = "video"
    elif auth_asset.res_type == 4:
        res_type = "scrawl"
    if auth_asset.res_type == 1: #图片资源
        auth_asset_path = "%s/%d" % (get_user_path(request.user, res_type, auth_asset.album_id), auth_asset.id)
    else:
        auth_asset_path = "%s/%d" % (get_user_path(request.user, res_type), auth_asset.id)
    print "auth_asset_path", auth_asset_path
    if os.path.isdir(os.path.join(MEDIA_ROOT, auth_asset_path)):
        __import__('shutil').rmtree(os.path.join(MEDIA_ROOT, auth_asset_path))
    auth_asset.delete()
    return SuccessResponse({"id":asset_id})
Пример #2
0
 def __init__(self, prnt, MainWindow):
     self.main = MainWindow
     self.__init_ctrls(prnt)
     self.__init_sizer()
     self.__create_undo_redo(_("Undo"))
     # disable if no undo files exist (to lessen user confusion)
     if not os.path.exists(utils.get_user_path(u'undo/original.bak')) or not\
         os.path.exists(utils.get_user_path(u'undo/renamed.bak')):
             self.undoRedo.Enable(False)
Пример #3
0
 def __init__(self, prnt, MainWindow):
     self.main = MainWindow
     self.__init_ctrls(prnt)
     self.__init_sizer()
     self.__create_undo_redo(_("Undo"))
     # disable if no undo files exist (to lessen user confusion)
     if not os.path.exists(utils.get_user_path(u'undo/original.bak')) or not\
         os.path.exists(utils.get_user_path(u'undo/renamed.bak')):
             self.undoRedo.Enable(False)
Пример #4
0
    def rename(self, event):
        """
        Write undo files first (safety first !), then attemp to perform
        the renaming operation.
        """
        itemsRenamed = 0
        error = False
        main.currentItem = None
        main.bottomWindow.display.mode = 'rename'
        utils.set_busy(True)
        main.picker.view.path.SetEditable(False)

        # adjust and sort items when recursively renaming folders
        if app.recursiveFolderOn and event != u'undo':
            main.set_status_msg(
                _(u"Adjusting %s recursive paths, please wait ...") %
                len(main.toRename), u'wait')

            progressDialog = classes.ProgressDialog(
                main, app.prefs, main.items,
                _(u"Adjusting %%% recursive paths, please wait ..."))

            if app.showTimes:
                t = time.time()

            def sort_test(n):
                return -n[1][0].count(os.sep)

            main.toRename.sort(key=sort_test)

            progressDialog.destroy()

            if app.showTimes:
                print("%s items recursive adjust : %s" % (len(main.toRename),
                                                          (time.time() - t)))

        if not error:
            main.set_status_msg(_(u"Renaming in progress, please wait ..."),
                                u'wait')

            # open undo files for writing
            try:
                self.originalFile = codecs.open(
                    utils.get_user_path(u'undo/original.bak'), 'w', "utf-8")
                self.renamedFile = codecs.open(
                    utils.get_user_path(u'undo/renamed.bak'), 'w', "utf-8")
            except IOError as (n, strerror):
                msg = strerror + _(
                    u"\nMake sure 'undo' directory exists and is read/write\n\nYou will not be able to undo!!\nDo you want to continue??"
                )
                title = _(u"Problem with undo!")
                if not utils.make_yesno_dlg(msg, title):
                    error = 'cancelled'
                dlg.Destroy()
Пример #5
0
def thumbnail_save(user, thumbnail, obj_type, obj_id):
    """
        保存图片的缩略图
        参数描述:
          user: 用户实体
          thumbnail: 图片文件实体
          obj_type: 图片属于哪类实体 。string.  待选项为  ('topic', 'topic_remark')
          obj_id:  图片所属实体的id
    coder: kamihati 2015/3/24   从gateway/views_topic.py转移到这里改为通用方法
    coder: kamihati 2015/6/3 此方法暂无用处。确认无用后要删除。
    """
    t_path = "%s/%d" % (get_user_path(user, obj_type), obj_id)
    if not os.path.lexists(os.path.join(MEDIA_ROOT, t_path)):
        os.makedirs(os.path.join(MEDIA_ROOT, t_path))  #不存在,则创建文件夹

    if thumbnail:
        cover_image_data = thumbnail.getvalue()
        if len(cover_image_data) > ALLOWED_IMG_UPLOAD_SIZE:
            return FailResponse(u'文件超过最大充许大小')
        cover_img = Image.open(StringIO.StringIO(cover_image_data))
        cover_ext = get_img_ext(cover_img)

        thumbnail_img = "%s/thumbnail_img%s" % (t_path, cover_ext)
        if os.path.isfile(MEDIA_ROOT + thumbnail_img):
            i = 0
            while True:
                thumbnail_img = "%s/thumbnail_img_%d_%s" % (t_path, i, cover_ext)
                if os.path.isfile(MEDIA_ROOT+thumbnail_img):
                    break
        cover_img.save(os.path.join(MEDIA_ROOT, thumbnail_img))
        return thumbnail_img
Пример #6
0
 def change_language(self, language, event):
     """Write given language to 'language.ini' file."""
     try:
         langFile = codecs.open(utils.get_user_path(u'language.ini'), 'w', 'utf-8')
     except IOError, error:
         utils.make_err_msg(unicode(error), u"Error")
         pass
Пример #7
0
 def change_language(self, language, event):
     """Write given language to 'language.ini' file."""
     try:
         langFile = codecs.open(utils.get_user_path(u'language.ini'), 'w', 'utf-8')
     except IOError, error:
         utils.make_err_msg(unicode(error), u"Error")
         pass
Пример #8
0
def update_avatar(request, image):
    img = Image.open(StringIO(image.getvalue()))
    ext = get_img_ext(img)
    if ext == None:
        return FailResponse(u"只充许上传图片文件(%s)" % ';'.join(ALLOWED_IMG_EXTENSION))
    
    user_path = get_user_path(request.user, "")
    user_abspath = os.path.join(MEDIA_ROOT, user_path)
    if not os.path.exists(user_abspath):
        os.makedirs(user_abspath)

    avatar_img = '%s/%d%s' % (user_path, request.user.id, ext)
    #print avatar_img
    img_large = img.resize((300, 300), Image.ANTIALIAS)
    img_large.save(os.path.join(MEDIA_ROOT, get_tile_image_name(avatar_img, 'l')))
    img_medium = img.resize((120, 120), Image.ANTIALIAS)
    img_medium.save(os.path.join(MEDIA_ROOT, get_tile_image_name(avatar_img, 'm')))
    img_small = img.resize((40, 40), Image.ANTIALIAS)
    img_small.save(os.path.join(MEDIA_ROOT, get_tile_image_name(avatar_img, 's')))
    
    request.user.avatar_img = avatar_img
    request.user.save()
#     return SuccessResponse({'large':request.build_absolute_uri(MEDIA_URL + get_tile_image_name(avatar_img, 'l')),
#                             'medium':request.build_absolute_uri(MEDIA_URL + get_tile_image_name(avatar_img, 'm')),
#                             'small':request.build_absolute_uri(MEDIA_URL + get_tile_image_name(avatar_img, 's'))})
    return SuccessResponse({'large':MEDIA_URL + get_tile_image_name(avatar_img, 'l'),
                            'medium':MEDIA_URL + get_tile_image_name(avatar_img, 'm'),
                            'small':MEDIA_URL + get_tile_image_name(avatar_img, 's')})
Пример #9
0
    def undo_last_rename(self, event):
        """
        Grabs names from .bak files and reverts them to their originals.

        Keep this separate from csv file functions for safety and stability.
        """

        original = []
        renamed = []
        utils.set_busy(True)
        try:
            originalFile = codecs.open(
                utils.get_user_path(u'undo/original.bak'), 'r', 'utf-8')
            renamedFile = codecs.open(utils.get_user_path(u'undo/renamed.bak'),
                                      'r', 'utf-8')
            for line in originalFile:
                original.append([line.strip(), False])
            for line in renamedFile:
                renamed.append([line.strip(), 1])

        except IOError as error:
            utils.make_err_msg(_(u"%s\n\nUndo Failed !!") % error, _(u"Error"))
            pass
        else:

            def get_name(x):
                return x[0]

            commonPrefix = os.path.commonprefix(map(get_name,
                                                    original)).rstrip(os.sep)
            if os.path.exists(commonPrefix):
                main.picker.view.path.SetValue(commonPrefix)
                main.picker.view.dirPicker.SetPath(commonPrefix)

            if not len(original) == 0:
                main.toRename = zip(
                    renamed, original)  #reverse order from original rename!
                main.currentItem = None
                main.display_results()
                main.rename_items(u'undo')
                main.menuFile.SaveLog.Enable(False)
            else:
                main.set_status_msg(_(u"Nothing to undo"), u'eyes')

        main.bottomWindow.set_undo_redo_type('check')
        utils.set_busy(False)
Пример #10
0
    def rename(self, event):
        """
        Write undo files first (safety first !), then attemp to perform
        the renaming operation.
        """
        itemsRenamed = 0
        error = False
        main.currentItem = None
        main.bottomWindow.display.mode = 'rename'
        utils.set_busy(True)
        main.picker.view.path.SetEditable(False)

        # adjust and sort items when recursively renaming folders
        if app.recursiveFolderOn and event != u'undo':
            main.set_status_msg(_(u"Adjusting %s recursive paths, please wait ...") % len(main.toRename), u'wait')

            progressDialog = classes.ProgressDialog(main, app.prefs, main.items,
                                                    _(u"Adjusting %%% recursive paths, please wait ..."))

            if app.showTimes:
                t = time.time()

            def sort_test(n):
                return -n[1][0].count(os.sep)

            main.toRename.sort(key=sort_test)

            progressDialog.destroy()

            if app.showTimes:
                print("%s items recursive adjust : %s" % (len(main.toRename), (time.time() - t)))

        if not error:
            main.set_status_msg(_(u"Renaming in progress, please wait ..."), u'wait')

            # open undo files for writing
            try:
                self.originalFile = codecs.open(utils.get_user_path(u'undo/original.bak'), 'w', "utf-8")
                self.renamedFile = codecs.open(utils.get_user_path(u'undo/renamed.bak'), 'w', "utf-8")
            except IOError as (n, strerror):
                msg = strerror + _(u"\nMake sure 'undo' directory exists and is read/write\n\nYou will not be able to undo!!\nDo you want to continue??")
                title = _(u"Problem with undo!")
                if not utils.make_yesno_dlg(msg, title):
                    error = 'cancelled'
                dlg.Destroy()
Пример #11
0
def edit_video_opus(auth_user, auth_asset, auth_opus, auth_opus_page, **kwargs):
    '''
    制作视频作品的播放资源文件
    editor: kamihati 2015/5/20
    :param auth_user:  提交用户
    :param auth_asset:  对应的用户个人素菜
    :param auth_opus:  对应的用户个人作品
    :param auth_opus_page: 对应的用户个人作品分页
    :param widget_story_unit:
    :return:
    '''
    json_file = open(os.path.join(MEDIA_ROOT, "opus_temp/video/1.json"), 'r')
    img_file = open(os.path.join(MEDIA_ROOT, "opus_temp/video/1.jpg"), "rb")
    json_data = json_file.read()
    json_file.close()

    json_data = json_data.replace("{video_url}", MEDIA_URL + auth_asset.res_path)
    json_data = json_data.replace("{video_id}", str(auth_asset.id))
    json_data = json_data.replace("{story_name}", auth_opus.title)
    json_data = json_data.replace("{actor_name}", kwargs['author_name'])
    json_data = json_data.replace("{sex}", u"男" if kwargs['sex'] == 1 else u"女")
    json_data = json_data.replace("{age}", str(kwargs['age']))
    json_data = json_data.replace("{school_name}", kwargs['school_name'])
    json_data = json_data.replace("{unit_name}", kwargs['unit_name'])
    json_data = json_data.replace("{number}", kwargs['number'])
    asset_res_path = get_user_path(auth_user, "opus", auth_opus.opus_id)
    if not os.path.exists(os.path.join(MEDIA_ROOT, asset_res_path)):
        os.makedirs(os.path.join(MEDIA_ROOT, asset_res_path))

    json_data = json_data.encode('utf-8')
    auth_opus_page.json = json_data
    auth_opus_page.save()
    open(os.path.join(MEDIA_ROOT, auth_opus_page.json_path), "w").write(json_data)

    img_data = img_file.read()
    img_file.close()
    img = Image.open(StringIO(img_data))

    font_file = fonts[1]["font"]
    font_file = os.path.join(FONT_ROOT, font_file)
    #print font_file
    dr = ImageDraw.Draw(img)
    font = ImageFont.truetype(font_file, 32)
    dr.text((1389,174), auth_opus.title, fill="#000000", font=font)
    dr.text((1392,227), kwargs['author_name'], fill="#000000", font=font)
    dr.text((1390,285), u"男" if kwargs['sex'] == 1 else u"女", fill="#000000", font=font)
    dr.text((1392,344), str(kwargs['age']), fill="#000000", font=font)
    dr.text((1394,399), kwargs['school_name'], fill="#000000", font=font)
    dr.text((1466,458), kwargs['number'], fill="#000000", font=font)

    if len(kwargs['unit_name']) > 9:
        dr.text((1466,519), kwargs['unit_name'][:9], fill="#000000", font=font)
        dr.text((1466,580), kwargs['unit_name'][9:], fill="#000000", font=font)
    else:
        dr.text((1466,519), kwargs['unit_name'], fill="#000000", font=font)
    img.save(os.path.join(MEDIA_ROOT, auth_opus_page.img_path))
Пример #12
0
    def undo_last_rename(self, event):
        """
        Grabs names from .bak files and reverts them to their originals.

        Keep this separate from csv file functions for safety and stability.
        """

        original = []
        renamed = []
        utils.set_busy(True)
        try:
            originalFile = codecs.open(utils.get_user_path(u'undo/original.bak'), 'r',
                                       'utf-8')
            renamedFile = codecs.open(utils.get_user_path(u'undo/renamed.bak'), 'r',
                                      'utf-8')
            for line in originalFile:
                original.append([line.strip(), False])
            for line in renamedFile:
                renamed.append([line.strip(), 1])

        except IOError as error:
            utils.make_err_msg(_(u"%s\n\nUndo Failed !!") % error, _(u"Error"))
            pass
        else:
            def get_name(x): return x[0]
            commonPrefix = os.path.commonprefix(map(get_name, original)).rstrip(os.sep)
            if os.path.exists(commonPrefix):
                main.picker.view.path.SetValue(commonPrefix)
                main.picker.view.dirPicker.SetPath(commonPrefix)

            if not len(original) == 0:
                main.toRename = zip(renamed, original)#reverse order from original rename!
                main.currentItem = None
                main.display_results()
                main.rename_items(u'undo')
                main.menuFile.SaveLog.Enable(False)
            else:
                main.set_status_msg(_(u"Nothing to undo"), u'eyes')

        main.bottomWindow.set_undo_redo_type('check')
        utils.set_busy(False)
Пример #13
0
def load(main, configFilePath=False):
    """Get config file path from dialog and apply settings."""
    if configFilePath:
        LoadConfig(main, configFilePath)
    else:
        dlg = wx.FileDialog(None,
                            message=_(u"Load a configuration file"),
                            defaultDir=utils.get_user_path('configs'), defaultFile=u'',
                            wildcard=_(u"Configuration file (*.cfg)") + u'|*.cfg',
                            style=wx.OPEN
                            )
        if dlg.ShowModal() == wx.ID_OK:
            LoadConfig(main, dlg.GetPath())
        dlg.Destroy()
Пример #14
0
def load(main, configFilePath=False):
    """Get config file path from dialog and apply settings."""
    if configFilePath:
        LoadConfig(main, configFilePath)
    else:
        dlg = wx.FileDialog(None,
                            message=_(u"Load a configuration file"),
                            defaultDir=utils.get_user_path('configs'),
                            defaultFile=u'',
                            wildcard=_(u"Configuration file (*.cfg)") +
                            u'|*.cfg',
                            style=wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            LoadConfig(main, dlg.GetPath())
        dlg.Destroy()
Пример #15
0
def update_story_opus(auth_user, auth_asset, widget_story_opus, auth_opus_page, widget_story_unit):
    json_file = open(os.path.join(MEDIA_ROOT, "gsdw/1.json"), 'r')
    img_file = open(os.path.join(MEDIA_ROOT, "gsdw/1.jpg"), "rb")
    json_data = json_file.read()
    json_file.close()
    
    json_data = json_data.replace("{video_url}", MEDIA_URL + auth_asset.res_path)
    json_data = json_data.replace("{video_id}", str(auth_asset.id))
    json_data = json_data.replace("{story_name}", widget_story_opus.story_name)
    json_data = json_data.replace("{actor_name}", widget_story_opus.actor_name)
    json_data = json_data.replace("{sex}", u"男" if widget_story_opus.sex==1 else u"女")
    json_data = json_data.replace("{age}", str(widget_story_opus.age))
    json_data = json_data.replace("{school_name}", widget_story_opus.school_name)
    json_data = json_data.replace("{unit_name}", widget_story_unit.name)
    json_data = json_data.replace("{number}", auth_user.number)
    #print json_data
    asset_res_path = get_user_path(auth_user, "opus", widget_story_opus.opus_id)
    if not os.path.exists(os.path.join(MEDIA_ROOT, asset_res_path)):
        os.makedirs(os.path.join(MEDIA_ROOT, asset_res_path))
    
    json_data = json_data.encode('utf-8')
    auth_opus_page.json = json_data
    auth_opus_page.save()
    open(os.path.join(MEDIA_ROOT, auth_opus_page.json_path), "w").write(json_data)
    
    img_data = img_file.read()
    img_file.close()
    img = Image.open(StringIO(img_data))
    from WebZone.conf import fonts
    from WebZone.settings import FONT_ROOT
    font_file = fonts[1]["font"]
    font_file = os.path.join(FONT_ROOT, font_file)
    #print font_file 
    dr = ImageDraw.Draw(img)
    font = ImageFont.truetype(font_file, 32)
    dr.text((1389,174), widget_story_opus.story_name, fill="#000000", font=font)
    dr.text((1392,227), widget_story_opus.actor_name, fill="#000000", font=font)
    dr.text((1390,285), u"男" if widget_story_opus.sex==1 else u"女", fill="#000000", font=font)
    dr.text((1392,344), str(widget_story_opus.age), fill="#000000", font=font)
    dr.text((1394,399), widget_story_opus.school_name, fill="#000000", font=font)
    dr.text((1466,458), auth_user.number, fill="#000000", font=font)
    
    if len(widget_story_unit.name) > 9:
        dr.text((1466,519), widget_story_unit.name[:9], fill="#000000", font=font)
        dr.text((1466,580), widget_story_unit.name[9:], fill="#000000", font=font)
    else:
        dr.text((1466,519), widget_story_unit.name, fill="#000000", font=font)
    img.save(os.path.join(MEDIA_ROOT, auth_opus_page.img_path))
Пример #16
0
def save(main):
    """Get values, write configuration file."""
    # save dialog
    dlg = wx.FileDialog(None, message=_(u"Save configuration as ..."),
                        defaultDir=utils.get_user_path(u'configs'), defaultFile=u'.cfg',
                        wildcard=_(u"Configuration file (*.cfg)") + u'|*.cfg',
                        style=wx.SAVE | wx.OVERWRITE_PROMPT
                        )
    # write file
    if dlg.ShowModal() == wx.ID_OK:
        cfgFilePath = dlg.GetPath()
        cfgFileExt = path.splitext(cfgFilePath)[1]
        if cfgFileExt != '.cfg':
            cfgFilePath = cfgFilePath + '.cfg'
        # create and write the file
        utils.write_file(cfgFilePath, SaveConfig(main).cfgFile)
    dlg.Destroy()
Пример #17
0
def save(main):
    """Get values, write configuration file."""
    # save dialog
    dlg = wx.FileDialog(None,
                        message=_(u"Save configuration as ..."),
                        defaultDir=utils.get_user_path(u'configs'),
                        defaultFile=u'.cfg',
                        wildcard=_(u"Configuration file (*.cfg)") + u'|*.cfg',
                        style=wx.SAVE | wx.OVERWRITE_PROMPT)
    # write file
    if dlg.ShowModal() == wx.ID_OK:
        cfgFilePath = dlg.GetPath()
        cfgFileExt = path.splitext(cfgFilePath)[1]
        if cfgFileExt != '.cfg':
            cfgFilePath = cfgFilePath + '.cfg'
        # create and write the file
        utils.write_file(cfgFilePath, SaveConfig(main).cfgFile)
    dlg.Destroy()
Пример #18
0
def delete_scrawl(request, param):
    if param.has_key("id"): scrawl_id = int(param.id)
    else: return FailResponse(u'输入需要删除的涂鸦ID')

    try: auth_asset = AuthAsset.objects.get(id=scrawl_id)
    except(AuthAsset.DoesNotExist): return FailResponse(u"请指定要删除的涂鸦的ID")

    if auth_asset.user_id <> request.user.id: return FailResponse(u'只能删除自己的资源')
    
    if auth_asset.ref_times > 0: return FailResponse(u'资源有(%s)个相关引用,不能删除' % auth_asset.ref_times)
    
    res_type = "scrawl"
    auth_asset_path = "%s/%d" % (get_user_path(request.user, res_type), auth_asset.id)
    #print "auth_asset_path", auth_asset_path
    if os.path.isdir(os.path.join(MEDIA_ROOT, auth_asset_path)):
        __import__('shutil').rmtree(os.path.join(MEDIA_ROOT, auth_asset_path))
    auth_asset.delete()
    return SuccessResponse({"id":scrawl_id})
Пример #19
0
def thumbnail_save(request, thumbnail, auth_topic):
    topic_path = "%s/%d" % (get_user_path(request.user, 'topic'), auth_topic.id)
    if not os.path.lexists(os.path.join(MEDIA_ROOT, topic_path)):
        os.makedirs(os.path.join(MEDIA_ROOT, topic_path))  #不存在,则创建文件夹
        
    if thumbnail:
        cover_image_data = thumbnail.getvalue()
        if len(cover_image_data) > ALLOWED_IMG_UPLOAD_SIZE:
            return FailResponse(u'文件超过最大充许大小')
        cover_img = Image.open(StringIO(cover_image_data))
        cover_ext = get_img_ext(cover_img)
        thumbnail_img = "%s/thumbnail_img%s" % (topic_path, cover_ext)
        if os.path.isfile(MEDIA_ROOT+thumbnail):
            i = 0 
            while True:
                thumbnail_img = "%s/thumbnail_img_%d_%s" % (topic_path, i, cover_ext)
                if os.path.isfile(MEDIA_ROOT+thumbnail_img):
                    break 
                  
        print "cover image:", os.path.join(MEDIA_ROOT, thumbnail_img) 
        cover_img.save(os.path.join(MEDIA_ROOT, thumbnail_img))
        return thumbnail_img
Пример #20
0
def update_camera_image(request, param):
    """
    新建,更新“我的自拍”照片
    """
    if param.has_key("image_data"):
        image_data = param.image_data.getvalue()
    else:
        return FailResponse(u'必须传入图片对象')
    
    if len(image_data) > ALLOWED_IMG_UPLOAD_SIZE:
        return FailResponse(u'文件超过最大充许大小')
    img = Image.open(StringIO(image_data))
    ext = get_img_ext(img)
    if ext == None:
        return FailResponse(u"只充许上传图片文件(%s)" % ';'.join(ALLOWED_IMG_EXTENSION))
    if param.has_key("title"): title = title = param.title
    else: title = datetime.now().strftime("%Y%m%d_%H:%M:%S")

    auth_album = get_camera_album(request.user)
    #print auth_album
    
    if param.has_key("id") and param.id:
        camear_id = param.id
        try: auth_asset = AuthAsset.objects.get(id=camear_id)
        except(AuthAsset.DoesNotExist): return FailResponse(u"请指定要修改的涂鸦的ID")
    else:
        auth_asset = AuthAsset()
        auth_asset.library = request.user.library
        auth_asset.user = request.user
        auth_asset.res_type = 1 #图片
        auth_asset.album_id = auth_album.id
        auth_asset.status = -1
    auth_asset.res_title = title
    auth_asset.save()
    
    asset_res_path = "%s/%d" % (get_user_path(request.user, 'image', auth_album.id), auth_asset.id)
    #print asset_res_path
    asset_res_abspath = os.path.join(MEDIA_ROOT, asset_res_path)
    if not os.path.lexists(asset_res_abspath):
        os.makedirs(asset_res_abspath)  #不存在,则创建文件夹

    auth_asset.res_path = '%s/origin%s' % (asset_res_path, ext)
    auth_asset.img_large_path = auth_asset.res_path.replace("origin", "l")
    auth_asset.img_medium_path = auth_asset.res_path.replace("origin", "m")
    auth_asset.img_small_path = auth_asset.res_path.replace("origin", "s")

    img.save(os.path.join(MEDIA_ROOT, auth_asset.res_path))
    
    origin_size = img.size
    auth_asset.width = origin_size[0]
    auth_asset.height = origin_size[1]
    
    if origin_size[0] > 950 or origin_size[1] > 950:
        img.thumbnail((950,950), Image.ANTIALIAS)
        img.save(os.path.join(MEDIA_ROOT, auth_asset.img_large_path))
    else:
        auth_asset.img_large_path = auth_asset.res_path
    
    if origin_size[0] > 600 or origin_size[1] > 600:
        img.thumbnail((600,600), Image.ANTIALIAS)
        img.save(os.path.join(MEDIA_ROOT, auth_asset.img_medium_path))
    else:
        auth_asset.img_medium_path = auth_asset.img_large_path
    
    im_small = ImageOps.fit(img, (240,190), Image.ANTIALIAS)
    im_small.save(os.path.join(MEDIA_ROOT, auth_asset.img_small_path))
    
    auth_asset.status = 1
    auth_asset.save()
    
    return SuccessResponse({'id':auth_asset.id, 'title':auth_asset.res_title, 
                            'origin':MEDIA_URL + auth_asset.res_path,
                            'large':MEDIA_URL + auth_asset.img_large_path,
                            'medium':MEDIA_URL + auth_asset.img_medium_path,
                            'small':MEDIA_URL + auth_asset.img_small_path})
Пример #21
0
def delete_story(request):
    try: story_opus_id = request.REQUEST['id']
    except: return HttpResponse(u"参数错误")
    
    try:
        widget_story_opus = WidgetStoryOpus.objects.get(id=story_opus_id)
        widget_story_unit = WidgetStoryUnit.objects.get(id=widget_story_opus.unit_id)
        widget_district = WidgetDistrict.objects.get(id=widget_story_unit.district_id)
    except: return HttpResponse(u"不存在的故事ID")
    
    log_content = u"%s删除了“故事达人”的作品:【%s】" % (request.user, widget_story_opus.story_name)
    
    auth_asset = widget_story_opus.auth_asset
    auth_user = widget_story_opus.user
    
    AuthAssetShare.objects.filter(auth_asset_id=auth_asset.id).delete()
    AuthAssetRef.objects.filter(auth_asset_id=auth_asset.id).delete()
    AuthOpusPage.objects.filter(auth_opus_id=widget_story_opus.opus_id).delete()
    auth_opus = AuthOpus.objects.filter(id=widget_story_opus.opus_id)
#     if auth_asset.ref_times > 0:
#         return HttpResponse(u'资源有(%s)个相关引用,不能删除' % auth_asset.ref_times)
#     if auth_asset.share_times > 0:
#         return HttpResponse(u'资源有(%s)个相关共享,不能删除' % auth_asset.ref_times)
    
    auth_asset_dir = '%s/%d' % (get_user_path(auth_asset.user, auth_asset.res_type), auth_asset.id)
    auth_asset_absdir = os.path.join(MEDIA_ROOT, auth_asset_dir)
    print "auth_asset_absdir", auth_asset_absdir
    __import__('shutil').rmtree(auth_asset_absdir)
    
#     opus_path = get_user_path(auth_opus.user, "opus", auth_opus.id)
#     opus_abspath = os.path.join(MEDIA_ROOT, opus_path)
#     print "opus_abspath", opus_abspath
#     __import__('shutil').rmtree(opus_abspath)
    #用户全删除,需要删除整个用户的目录,不仅仅是作品
    user_path = 'user/%d/%s/%d' % (auth_user.library.id, auth_user.date_joined.strftime("%Y"), auth_user.id)
    user_abspath = os.path.join(MEDIA_ROOT, user_path)
    print "user_abspath", user_abspath
    __import__('shutil').rmtree(user_abspath)
    
    auth_user.delete()
    auth_opus.delete()
    
    widget_story_opus.delete()
    auth_asset.delete()
    widget_story_unit.story_count -= 1
    widget_story_unit.save()
    widget_district.story_count -= 1
    widget_district.save()
    
    #记录日志
    add_manager_action_log(request, log_content)
    return HttpResponse('ok')

    
    
    
    
    
    
    
    
    
    
    
    
    
Пример #22
0
def story_opus(request):
    """
        添加选手作品
    """
    if request.method == "GET":
        story_opus_id = request.REQUEST.get('id', None)
        story_opus = None
        if story_opus_id:
            try: story_opus = WidgetStoryOpus.objects.get(id=story_opus_id)
            except: pass
        return render(request, "manager/story_opus.html", {"index":7, "sub_index":2, "story_opus":story_opus})
    elif request.method == "POST":
        try:
            unit_id = int(request.REQUEST["sel_unit"])    #报送单位ID
            story_name = request.REQUEST["story_name"].strip()
            story_brief = request.REQUEST["story_brief"].strip()
            actor_name = request.REQUEST["actor_name"].strip()
            actor_brief = request.REQUEST["actor_brief"].strip()
            group_id = int(request.REQUEST["rdo_group"])
            sex = int(request.REQUEST["rdo_sex"])
            age = request.REQUEST["age"]
            school_name = request.REQUEST["school_name"].strip()
            telephone = request.REQUEST["telephone"].strip()
            email = request.REQUEST["email"].strip()
            
            story_file = request.FILES.get("story_file", None)
            
            hid_story_id = request.REQUEST["hid_story_id"]
            #print group_id, sex
        except:
            #traceback.print_exc()
            return HttpResponse(u"参数错误")

        try: widget_story_unit = WidgetStoryUnit.objects.get(id=unit_id)
        except: return HttpResponse(u"必须选择报送单位")
        if not hid_story_id and not story_file:
            return HttpResponse(u'必须上传视频文件')
        
        is_change_district = False #改变作品的区域
        action_name = u"新上传"
        if hid_story_id:
            action_name = u"修改"
            try:
                widget_story_opus = WidgetStoryOpus.objects.get(id=hid_story_id)
                
                if widget_story_opus.unit_id <> widget_story_unit.id:
                    is_change_district = True
                    story_unit = WidgetStoryUnit.objects.get(id=widget_story_opus.unit_id)
                    #更新所在区域,上报单位拥有作品数量
                    update_story_count(story_unit, -1)
                
                widget_story_opus.district_id = widget_story_unit.district_id
                widget_story_opus.unit_id = unit_id
                widget_story_opus.group_id = group_id
                widget_story_opus.story_name = story_name
                widget_story_opus.story_brief = story_brief
                widget_story_opus.actor_name = actor_name
                widget_story_opus.actor_brief = actor_brief
                widget_story_opus.sex = sex
                widget_story_opus.age = age
                widget_story_opus.school_name = school_name
                widget_story_opus.telephone = telephone
                widget_story_opus.email = email
                widget_story_opus.update_time = datetime.now()
                widget_story_opus.save()
                
                auth_asset = widget_story_opus.auth_asset
                if story_file:
                    ext = os.path.splitext(story_file.name)[1]
                    if ext.lower() not in ALLOWED_VIDEO_EXTENSION:
                        return HttpResponse(u"只充许上传视频文件(%s)" % ';'.join(ALLOWED_VIDEO_EXTENSION))
                    if story_file.size > ALLOWED_VIDEO_UPLOAD_SIZE:
                        return HttpResponse(u'文件超过最大充许大小')
                    
                    #注意,视频上传到管理员的目录里, 不是注册用户的目录里
                    asset_res_path = "%s/%d" % (get_user_path(request.user, auth_asset.res_type), auth_asset.id)
                    if not os.path.exists(os.path.join(MEDIA_ROOT, asset_res_path)):
                        os.makedirs(os.path.join(MEDIA_ROOT, asset_res_path))
                    auth_asset.origin_path = '%s/origin%s' % (asset_res_path, ext)
                    auth_asset.res_path = '%s/%d.flv' % (asset_res_path, auth_asset.id)
                    auth_asset.img_large_path = '%s/l.jpg' % asset_res_path #存视频截图的原图
                    auth_asset.img_small_path = '%s/s.jpg' % asset_res_path
                    f = open(os.path.join(MEDIA_ROOT, auth_asset.origin_path), "wb")    #待转码状态
                    for chunk in story_file.chunks():
                        f.write(chunk)
                    f.close()
                    auth_asset.codec_status = 0 #更新视频了,需要重新转码
                    auth_asset.status = 1
                    auth_asset.save()
                
                auth_user = widget_story_opus.user
                auth_user.set_password(telephone.strip().lower())   #修改密码
                auth_user.save()
                
                auth_opus_page = AuthOpusPage.objects.get(auth_opus_id=widget_story_opus.opus_id, page_index=1)
                
                #更新作品背景
                update_story_opus(auth_user, auth_asset, widget_story_opus, auth_opus_page, widget_story_unit)
            except:
                traceback.print_exc()
                return HttpResponse(u"故事ID不存在")
        else:
            auth_asset = AuthAsset()
            auth_asset.library = request.user.library
            auth_asset.user = request.user
            auth_asset.res_title = story_name
            auth_asset.res_type = 11    #故事大王专题
            auth_asset.status = -1  #未上传成功前,先状态为-1
            auth_asset.ref_times = 1
            auth_asset.share_times = 1
            auth_asset.save()   #得到ID
            if story_file:
                filename, ext = os.path.splitext(story_file.name)
                if ext.lower() not in ALLOWED_VIDEO_EXTENSION:
                    return HttpResponse(u"只充许上传视频文件(%s)" % ';'.join(ALLOWED_VIDEO_EXTENSION))
                if story_file.size > ALLOWED_VIDEO_UPLOAD_SIZE:
                    return HttpResponse(u'文件超过最大充许大小')
                
                #注意,视频上传到管理员的目录里, 不是注册用户的目录里
                asset_res_path = "%s/%d" % (get_user_path(request.user, auth_asset.res_type), auth_asset.id)
                if not os.path.exists(os.path.join(MEDIA_ROOT, asset_res_path)):
                    os.makedirs(os.path.join(MEDIA_ROOT, asset_res_path))
                auth_asset.origin_path = '%s/origin%s' % (asset_res_path, ext)
                auth_asset.res_path = '%s/%d.flv' % (asset_res_path, auth_asset.id)
                auth_asset.img_large_path = '%s/l.jpg' % asset_res_path #存视频截图的原图
                auth_asset.img_small_path = '%s/s.jpg' % asset_res_path
                f = open(os.path.join(MEDIA_ROOT, auth_asset.origin_path), "wb")    #待转码状态
                for chunk in story_file.chunks():
                    f.write(chunk)
                f.close()
                auth_asset.status = 1
                auth_asset.save()
            
            widget_story_opus = WidgetStoryOpus()
            widget_story_opus.library = request.user.library
            widget_story_opus.auth_asset = auth_asset
            widget_story_opus.district_id = widget_story_unit.district_id
            widget_story_opus.unit_id = unit_id
            widget_story_opus.group_id = group_id
            widget_story_opus.story_name = story_name
            widget_story_opus.story_brief = story_brief
            widget_story_opus.actor_name = actor_name
            widget_story_opus.actor_brief = actor_brief
            widget_story_opus.sex = sex
            widget_story_opus.age = age
            widget_story_opus.school_name = school_name
            widget_story_opus.telephone = telephone
            widget_story_opus.email = email
            widget_story_opus.save()
            
            #自动生成一个会员,账号是telephone,密码是111111
            auth_user = AuthUser()
            auth_user.number = new_number()
            auth_user.username = "******" % auth_user.number
            auth_user.set_password(telephone.strip().lower())
            auth_user.library_id = 1    #省少儿图书馆id
            auth_user.nickname = actor_name
            auth_user.realname = actor_name
            auth_user.auth_type = 11    #故事大王会员
            auth_user.sex = sex
            auth_user.telephone = telephone
            auth_user.school = school_name
            auth_user.email = email
            auth_user.reg_ip = get_ip(request)
            auth_user.last_ip = auth_user.reg_ip
            auth_user.save()
            #把资源共享给新建用户
            auth_asset_share = AuthAssetShare()
            auth_asset_share.auth_asset = auth_asset
            auth_asset_share.user = auth_user
            auth_asset_share.save()
            
            #用默认故事大王模板,直接创建作品
            auth_opus = AuthOpus()
            auth_opus.user = auth_user
            auth_opus.library_id = 1    #省少儿图书馆id
            auth_opus.title = widget_story_opus.story_name
            auth_opus.brief = widget_story_opus.story_brief
            auth_opus.show_type = 101   #故事大王大赛的风格
            auth_opus.type_id = 2   #才艺展示
            auth_opus.class_id = 24    #讲故事
            auth_opus.page_count = 1
            auth_opus.width = 1812
            auth_opus.height = 870
            auth_opus.status = 1    #待审核    自动转码成功后,转为已发表状态
            auth_opus.save()
            #创建资源的引用表
            auth_asset_ref = AuthAssetRef()
            auth_asset_ref.auth_asset = auth_asset
            auth_asset_ref.user = auth_user
            auth_asset_ref.auth_opus = auth_opus
            auth_asset_ref.page_index = 1
            auth_asset_ref.res_type = auth_opus.type_id
            auth_asset_ref.save()
            
            opus_res_path = get_user_path(auth_user, "opus", auth_opus.id)
            auth_opus_page = AuthOpusPage()
            auth_opus_page.auth_opus = auth_opus
            auth_opus_page.page_index = 1
            auth_opus_page.is_multimedia = 1
            auth_opus_page.auth_asset_list = int(auth_asset.id)
            #auth_opus_page.json = ""
            auth_opus_page.json_path = "%s/1.json" % opus_res_path
            auth_opus_page.img_path = "%s/1.jpg" % opus_res_path
            auth_opus_page.img_small_path = "%s/1_s.jpg" % opus_res_path
            auth_opus_page.save()
            
            widget_story_opus.user_id = auth_user.id    #自动创建用户ID
            widget_story_opus.opus_id = auth_opus.id    #自动创建作品ID
            widget_story_opus.save()
            update_story_opus(auth_user, auth_asset, widget_story_opus, auth_opus_page, widget_story_unit)
            
        #更新所在区域,上报单位拥有作品数量
        if hid_story_id and is_change_district:    #旧作品,但更新作品区域的话
            update_story_count(widget_story_unit, 1)
        else: update_story_count(widget_story_unit, 1)  #新作品
        
        #记录日志
        add_manager_action_log(request, u'%s%s了“故事达人”作品【%s】' % (request.user, action_name, widget_story_opus.story_name))
        
        return render(request, "manager/story_opus.html", {"index":7, "sub_index":2, "result":"ok", "username":auth_user.username, "password":auth_user.telephone.strip().lower()})
Пример #23
0
    def set_language(self):
        """
        Determine language to be loaded depending on : setting file, CLI option,
        or neither.
        Apply language to interface.
        """
        app.debug_print("== Interface Localization ==")

        # reference:
        locales = {
            #u'ar' : (wx.LANGUAGE_ARABIC, u'ar_SA.UTF-8'),
            #u'de' : (wx.LANGUAGE_GERMAN, u'de_DE.UTF-8'),
            #u'el' : (wx.LANGUAGE_GREEK, u'el_GR.UTF-8'),
            #u'en_GB' : (wx.LANGUAGE_ENGLISH_UK, u'en_GB.UTF-8'),
            u'en_US': (wx.LANGUAGE_ENGLISH_US, u'en_US.UTF-8'),
            u'es': (wx.LANGUAGE_SPANISH, u'es_ES.UTF-8'),
            u'fr': (wx.LANGUAGE_FRENCH, u'fr_FR.UTF-8'),
            #u'he' : (wx.LANGUAGE_HEBREW, u'he_IL.UTF-8'),
            #u'hu' : (wx.LANGUAGE_HUNGARIAN, u'hu_HU.UTF-8'),
            #u'it' : (wx.LANGUAGE_ITALIAN, u'it_IT.UTF-8'),
            #u'ja' : (wx.LANGUAGE_JAPANESE, u'ja_JP.UTF-8'),
            #u'pl' : (wx.LANGUAGE_POLISH, u'pl_PL.UTF-8'),
            #u'pt_BR' : (wx.LANGUAGE_PORTUGUESE_BRAZILIAN, u'pt_BR.UTF-8'),
            #u'ru' : (wx.LANGUAGE_RUSSIAN, u'ru_RU.UTF-8'),
            #u'sv' : (wx.LANGUAGE_SWEDISH, u'sv_SE.UTF-8'),
            #u'tr' : (wx.LANGUAGE_TURKISH, u'tr_TR.UTF-8'),
            #u'zh_CN' : (wx.LANGUAGE_CHINESE_SIMPLIFIED, u'zh_CN.UTF-8'),
        }

        # right-to-left languages:
        rightToLeftLanguages = ('ar', 'dv', 'fa', 'ha', 'he', 'ps', 'ur', 'yi')
        '''
        syslang = locale.getdefaultlocale()[0]
        if syslang in locales:
            language = syslang
        '''
        # get language from file if not specified from command line
        if not app.language:
            try:  # see if language file exist
                langIni = codecs.open(utils.get_user_path(u'language.ini'), 'r', 'utf-8')
            except IOError:  # have user choose language
                language = self.language_select(0)
            else:  # get language from file
                language = langIni.read().strip()
        else:
            language = app.language

        try:
            locales[language]
        except KeyError:
            msg = u"Could not initialize language: '%s'.\nContinuing in " % language
            msg += u"American English (en_US)\n"
            print(msg)
            language = 'en_US'

        # needed for calendar and other things, send all logs to stderr
        wx.Log.SetActiveTarget(wx.LogStderr())

        # set locale and language
        wx.Locale(locales[language][0], wx.LOCALE_LOAD_DEFAULT)

        try:
            Lang = gettext.translation(u'metamorphose2', app.locale_path(language),
                                       languages=[locales[language][1]])
        except IOError:
            print("Could not find the translation file for '%s'." % language)
            print("Try running messages/update_langs.sh\n")
            sys.exit(1)

        Lang.install(unicode=True)

        # set some globals
        if language not in rightToLeftLanguages:
            self.langLTR = True
            self.alignment = wx.ALIGN_LEFT
        else:
            self.langLTR = False
            self.alignment = wx.ALIGN_RIGHT
        app.language = language
        app.debug_print("Set language: " + app.language)

        locale.setlocale(locale.LC_ALL,'')
        self.encoding = unicode(locale.getlocale()[1])
        app.debug_print("Set encoding: " + self.encoding)

        # to get some language settings to display properly:
        if platform.system() in ('Linux', 'FreeBSD'):
            try:
                os.environ['LANG'] = locales[language][1]
            except (ValueError, KeyError):
                pass
        app.debug_print("============================")
        app.debug_print("")
Пример #24
0
def edit_video_fruit(file_path, fruit_type,  *ages, **kwargs):
    '''
    编辑活动作品
    editor: kamihati 2015/5/20
    :param user_id:  添加人
    :param ages:
    :param kwargs:
    :return:
    '''
    from library.models import Library
    from activity.models import ActivityList
    from account.models import AuthUser
    from diy.models import AuthOpus, AuthOpusPage, AuthAssetRef, AuthAsset, AuthAssetShare

    library = Library.objects.get(pk=kwargs['library_id'])
    activity = ActivityList.objects.get(pk=kwargs['activity_id'])
    user = AuthUser.objects.get(pk=kwargs['user_id'])

    # 获取用户资源
    auth_asset = AuthAsset()
    auth_asset.library = library
    auth_asset.user = user
    auth_asset.res_title = kwargs['title']
    # 导入根据fruit_type 得到res_type的方法
    # res_type  ((1,u"图片"),(2,u"声音"),(3,u"视频"))
    from activity.handler import get_res_type_by_fruit_type
    auth_asset.res_type = get_res_type_by_fruit_type(fruit_type)
    auth_asset.status = -1  #未上传成功前,先状态为-1
    auth_asset.ref_times = 1
    auth_asset.share_times = 1
    auth_asset.save()   #得到ID

    auth_opus = AuthOpus()
    if auth_asset.res_type == 1:
        # 声音文件的处理
        pass
    elif auth_asset.res_path == 2:
        # 图片文件的处理
        pass
    elif auth_asset.res_path == 3:
        # 视频文件的处理
        filename, ext = os.path.splitext(file_path)
        if ext.lower() not in ALLOWED_VIDEO_EXTENSION:
            return -1, u"只充许上传视频文件(%s)" % ';'.join(ALLOWED_VIDEO_EXTENSION)

        asset_res_path = "%s/%d" % (get_user_path(user, auth_asset.res_type), auth_asset.id)
        if not os.path.exists(os.path.join(MEDIA_ROOT, asset_res_path)):
            os.makedirs(os.path.join(MEDIA_ROOT, asset_res_path))
        auth_asset.origin_path = '%s/origin%s' % (asset_res_path, ext)
        auth_asset.res_path = '%s/%d.flv' % (asset_res_path, auth_asset.id)
        auth_asset.img_large_path = '%s/l.jpg' % asset_res_path
        auth_asset.img_small_path = '%s/s.jpg' % asset_res_path
        # 需要进行转码
        move_temp_file(file_path, asset_res_path + "/origin")
        auth_asset.status = 1
        auth_asset.save()

        # 视频作品按照原故事达人的模版进行处理

        auth_opus.user = user
        auth_opus.library_id = kwargs['library_id']
        auth_opus.title = kwargs['title']
        auth_opus.brief = kwargs['brief']
        auth_opus.show_type = 101   #故事大王大赛的风格
        auth_opus.type_id = 2   #才艺展示
        auth_opus.class_id = 24    #讲故事
        auth_opus.page_count = 1
        auth_opus.width = 1812
        auth_opus.height = 870
        auth_opus.status = 1    #待审核    自动转码成功后,转为已发表状态
        auth_opus.save()

        #创建资源的引用表
        auth_asset_ref = AuthAssetRef()
        auth_asset_ref.auth_asset = auth_asset
        auth_asset_ref.user = user
        auth_asset_ref.auth_opus = auth_opus
        auth_asset_ref.page_index = 1
        auth_asset_ref.res_type = auth_opus.type_id
        auth_asset_ref.save()

        opus_res_path = get_user_path(user, "opus", auth_opus.id)
        auth_opus_page = AuthOpusPage()
        auth_opus_page.auth_opus = auth_opus
        auth_opus_page.page_index = 1
        auth_opus_page.is_multimedia = 1
        auth_opus_page.auth_asset_list = int(auth_asset.id)
        auth_opus_page.json_path = "%s/1.json" % opus_res_path
        auth_opus_page.img_path = "%s/1.jpg" % opus_res_path
        auth_opus_page.img_small_path = "%s/1_s.jpg" % opus_res_path
        auth_opus_page.save()
        # 制作视频创作
        edit_video_opus(user, auth_asset, auth_opus, auth_opus_page,
                        author_name=kwargs['author_name'],
                        sex=kwargs['sex'],
                        age=kwargs['age'],
                        school_name=kwargs['school_name'],
                        unit_name=kwargs['unit_name'],
                        number=kwargs['number'])
Пример #25
0
    def set_language(self):
        """
        Determine language to be loaded depending on : setting file, CLI option,
        or neither.
        Apply language to interface.
        """
        app.debug_print("== Interface Localization ==")

        # reference:
        locales = {
            #u'ar' : (wx.LANGUAGE_ARABIC, u'ar_SA.UTF-8'),
            #u'de' : (wx.LANGUAGE_GERMAN, u'de_DE.UTF-8'),
            #u'el' : (wx.LANGUAGE_GREEK, u'el_GR.UTF-8'),
            #u'en_GB' : (wx.LANGUAGE_ENGLISH_UK, u'en_GB.UTF-8'),
            u'en_US': (wx.LANGUAGE_ENGLISH_US, u'en_US.UTF-8'),
            u'es': (wx.LANGUAGE_SPANISH, u'es_ES.UTF-8'),
            u'fr': (wx.LANGUAGE_FRENCH, u'fr_FR.UTF-8'),
            #u'he' : (wx.LANGUAGE_HEBREW, u'he_IL.UTF-8'),
            #u'hu' : (wx.LANGUAGE_HUNGARIAN, u'hu_HU.UTF-8'),
            #u'it' : (wx.LANGUAGE_ITALIAN, u'it_IT.UTF-8'),
            #u'ja' : (wx.LANGUAGE_JAPANESE, u'ja_JP.UTF-8'),
            #u'pl' : (wx.LANGUAGE_POLISH, u'pl_PL.UTF-8'),
            #u'pt_BR' : (wx.LANGUAGE_PORTUGUESE_BRAZILIAN, u'pt_BR.UTF-8'),
            #u'ru' : (wx.LANGUAGE_RUSSIAN, u'ru_RU.UTF-8'),
            #u'sv' : (wx.LANGUAGE_SWEDISH, u'sv_SE.UTF-8'),
            #u'tr' : (wx.LANGUAGE_TURKISH, u'tr_TR.UTF-8'),
            #u'zh_CN' : (wx.LANGUAGE_CHINESE_SIMPLIFIED, u'zh_CN.UTF-8'),
        }

        # right-to-left languages:
        rightToLeftLanguages = ('ar', 'dv', 'fa', 'ha', 'he', 'ps', 'ur', 'yi')
        '''
        syslang = locale.getdefaultlocale()[0]
        if syslang in locales:
            language = syslang
        '''
        # get language from file if not specified from command line
        if not app.language:
            try:  # see if language file exist
                langIni = codecs.open(utils.get_user_path(u'language.ini'), 'r', 'utf-8')
            except IOError:  # have user choose language
                language = self.language_select(0)
            else:  # get language from file
                language = langIni.read().strip()
        else:
            language = app.language

        try:
            locales[language]
        except KeyError:
            msg = u"Could not initialize language: '%s'.\nContinuing in " % language
            msg += u"American English (en_US)\n"
            print(msg)
            language = 'en_US'

        # needed for calendar and other things, send all logs to stderr
        wx.Log.SetActiveTarget(wx.LogStderr())

        # set locale and language
        wx.Locale(locales[language][0], wx.LOCALE_LOAD_DEFAULT)

        try:
            Lang = gettext.translation(u'metamorphose2', app.locale_path(language),
                                       languages=[locales[language][1]])
        except IOError:
            print("Could not find the translation file for '%s'." % language)
            print("Try running messages/update_langs.sh\n")
            sys.exit(1)

        Lang.install(unicode=True)

        # set some globals
        if language not in rightToLeftLanguages:
            self.langLTR = True
            self.alignment = wx.ALIGN_LEFT
        else:
            self.langLTR = False
            self.alignment = wx.ALIGN_RIGHT
        app.language = language
        app.debug_print("Set language: " + app.language)

        self.encoding = unicode(locale.getlocale()[1])
        app.debug_print("Set encoding: " + self.encoding)

        # to get some language settings to display properly:
        if platform.system() in ('Linux', 'FreeBSD'):
            try:
                os.environ['LANG'] = locales[language][1]
            except (ValueError, KeyError):
                pass
        app.debug_print("============================")
        app.debug_print("")
Пример #26
0
def join_topic(request, param):
    """
        参与话题
    """
    if param.has_key("topic_id"): topic_id = int(param.topic_id)
    else: return FailResponse(u"必须指定话题ID")
    if param.has_key("mark_id"): mark_id = int(param.mark_id)
    else: return FailResponse(u"必须指定话题模板")
    if param.has_key("emotion_id"): emotion_id = int(param.emotion_id)
    else: return FailResponse(u"必须指定话题的分类")
    if param.has_key("content") or not param.content: content = param.content
    else: return FailResponse(u"必须输入你的话题")
    if param.has_key("img_data") or not param.img_data: img_data = param.img_data
    else: return FailResponse(u"必须传输话题图片")

    try: auth_topic = AuthTopic.objects.get(id=topic_id)
    except(AuthTopic.DoesNotExist): return FailResponse(u"指定的话题ID:%d不存在" % topic_id)

    img_data = img_data.getvalue()
    if len(img_data) > ALLOWED_IMG_UPLOAD_SIZE:
        return FailResponse(u'文件超过最大充许大小')
    img = Image.open(StringIO(img_data))
    img_ext = get_img_ext(img)
    if img_ext == None:
        return FailResponse(u"只充许上传图片文件(%s)" % ';'.join(ALLOWED_IMG_EXTENSION))

    auth_topic_page = AuthTopicPage()
    auth_topic_page.user_id = request.user.id
    auth_topic_page.library_id = request.user.library_id
    auth_topic_page.auth_topic_id = auth_topic.id
    auth_topic_page.mark_id = mark_id
    auth_topic_page.emotion_id = emotion_id
    auth_topic_page.content = content
    auth_topic_page.url = ""
    auth_topic_page.status = -1
    auth_topic_page.save()

    topic_user = AuthUser.objects.get(id=auth_topic.user_id)
    auth_topic_page.url = "%s/%d/%d%s" % (get_user_path(topic_user, 'topic'), auth_topic.id, auth_topic_page.id, img_ext)
    img.save(os.path.join(MEDIA_ROOT, auth_topic_page.url))

    auth_topic_page.status = 1
    auth_topic_page.save()
    auth_topic.join_count += 1
    auth_topic.save()

    #更新话题的页码,顺序
    #auth_topic_count = AuthTopicPage.objects.filter(auth_topic_id=auth_topic.id,status=1,id__gte=auth_topic_page.id).count()
    page_size = auth_topic.row_num * auth_topic.col_num
    auth_topic_page.page_index = auth_topic.join_count / page_size
    if auth_topic.join_count % page_size: auth_topic_page.page_index += 1
    auth_topic_page.page_order = auth_topic.join_count % page_size
    if auth_topic_page.page_order == 0:
        auth_topic_page.page_order = page_size
    auth_topic_page.save()

    back_dict = {"id":auth_topic_page.id, "auth_topic_id":auth_topic.id, "page_index":auth_topic_page.page_index, "page_order":auth_topic_page.page_order}
    back_dict["url"] = MEDIA_URL + auth_topic_page.url
    back_dict["page_count"] = auth_topic_page.page_index

    return SuccessResponse(back_dict)
Пример #27
0
def update_scrawl(request, param):
    """
        新建,更新涂鸦作品
        传入一个param对象参数,对象的成员如下:
        param.id    涂鸦ID,为空时是新建,有值时为更新
        param.title
        param.image_data
    """
    image_data = param.image_data.getvalue()
    if len(image_data) > ALLOWED_IMG_UPLOAD_SIZE:
        return FailResponse(u'文件超过最大充许大小')
    img = Image.open(StringIO(image_data))
    ext = get_img_ext(img)
    if ext == None:
        return FailResponse(u"只充许上传图片文件(%s)" % ';'.join(ALLOWED_IMG_EXTENSION))
    if len(param.title) == 0:
        return FailResponse(u"请输入此涂鸦的标题")

    auth_asset = None
    if param.has_key("id") and param.id:
        scrawl_id = param.id
        try: auth_asset = AuthAsset.objects.get(id=scrawl_id)
        except(AuthAsset.DoesNotExist): return FailResponse(u"请指定要修改的涂鸦的ID")
    else:
        auth_asset = AuthAsset()
        auth_asset.library = request.user.library
        auth_asset.user = request.user
        auth_asset.res_type = 4     #涂鸦
        auth_asset.status = -1
    auth_asset.res_title = param.title
    auth_asset.save()
    
    asset_res_path = "%s/%d" % (get_user_path(request.user, 'scrawl'), auth_asset.id)
    asset_res_abspath = os.path.join(MEDIA_ROOT, asset_res_path)
    if not os.path.lexists(asset_res_abspath):
        os.makedirs(asset_res_abspath)  #不存在,则创建文件夹

    auth_asset.res_path = '%s/origin%s' % (asset_res_path, ext)
    auth_asset.img_large_path = auth_asset.res_path.replace("origin", "l")
    auth_asset.img_medium_path = auth_asset.res_path.replace("origin", "m")
    auth_asset.img_small_path = auth_asset.res_path.replace("origin", "s")

    img.save(os.path.join(MEDIA_ROOT, auth_asset.res_path))
    
    origin_size = img.size
    auth_asset.width = origin_size[0]
    auth_asset.height = origin_size[1]
    
    if origin_size[0] > 950 or origin_size[1] > 950:
        img.thumbnail((950,950), Image.ANTIALIAS)
        img.save(os.path.join(MEDIA_ROOT, auth_asset.img_large_path))
    else:
        auth_asset.img_large_path = auth_asset.res_path
    
    if origin_size[0] > 600 or origin_size[1] > 600:
        img.thumbnail((600,600), Image.ANTIALIAS)
        img.save(os.path.join(MEDIA_ROOT, auth_asset.img_medium_path))
    else:
        auth_asset.img_medium_path = auth_asset.img_large_path
    
    im_small = ImageOps.fit(img, (240,190), Image.ANTIALIAS)
    im_small.save(os.path.join(MEDIA_ROOT, auth_asset.img_small_path))
    
    auth_asset.status = 1
    auth_asset.save()
    
    return SuccessResponse({'id':auth_asset.id, 'title':auth_asset.res_title, 
                            'origin':MEDIA_URL + auth_asset.res_path,
                            'large':MEDIA_URL + auth_asset.img_large_path,
                            'medium':MEDIA_URL + auth_asset.img_medium_path,
                            'small':MEDIA_URL + auth_asset.img_small_path})
Пример #28
0
def upload_personal_res(request):
    if len(request.FILES) == 0:
        return HttpResponse(FailResponse(u"请选择文件并上传"))
    elif len(request.FILES) > 1:
        return HttpResponse(FailResponse(u"一次只能上传一个文件"))
    res_title = request.REQUEST.get("res_title", None)
    res_type = request.REQUEST.get("res_type", "image").lower()
    album_id = int(request.REQUEST.get("album_id", 0))
    #print res_title, res_type, album_id
    if res_type not in ('image','sound','video'):
        return HttpResponse(FailResponse(u'资源类型(%s)不正确' % res_type))
    mem_file = request.FILES.popitem()[1][0]
    filename, ext = os.path.splitext(mem_file.name)
    if res_title == None: res_title = filename
    auth_asset = AuthAsset()
    auth_asset.library = request.user.library
    auth_asset.user = request.user
    auth_asset.res_title = res_title
    auth_asset.status = -1
    auth_asset.save()
    print 'begin.upload.res_type=', res_type
    if res_type == "image":
        if album_id == 0:
            auth_album = get_default_album(request.user.id)
            if auth_album:
                album_id = auth_album.id
            else:
                return HttpResponse(FailResponse(u'系统异常,请联系管理员'))
        elif AuthAlbum.objects.filter(id=album_id).count() == 0:
            return HttpResponse(FailResponse(u'相册ID:%d不存在' % album_id))
        auth_asset.album_id = album_id
        auth_asset.res_type = 1 #图片资源
        if ext.lower() not in ALLOWED_IMG_EXTENSION:
            return HttpResponse(FailResponse(u"只充许上传图片文件(%s)" % ';'.join(ALLOWED_IMG_EXTENSION)))
        if mem_file.size > ALLOWED_IMG_UPLOAD_SIZE:
            return HttpResponse(FailResponse(u'文件超过最大充许大小'))
        asset_res_path = "%s/%d" % (get_user_path(request.user, res_type, album_id), auth_asset.id)
        asset_res_abspath = os.path.join(MEDIA_ROOT, asset_res_path)
        os.makedirs(asset_res_abspath)  #创建文件夹
        auth_asset.res_path = '%s/origin%s' % (asset_res_path, ext)
        auth_asset.img_large_path = auth_asset.res_path.replace("origin", "l")
        auth_asset.img_medium_path = auth_asset.res_path.replace("origin", "m")
        auth_asset.img_small_path = auth_asset.res_path.replace("origin", "s")
        f = open(os.path.join(MEDIA_ROOT, auth_asset.res_path), "wb")
        for chunk in mem_file.chunks():
            f.write(chunk)
        f.close()

        img = Image.open(os.path.join(MEDIA_ROOT, auth_asset.res_path))
        origin_size = img.size
        auth_asset.width = origin_size[0]
        auth_asset.height = origin_size[1]
        
        if origin_size[0] > 950 or origin_size[1] > 950:
            img.thumbnail((950,950), Image.ANTIALIAS)
            img.save(os.path.join(MEDIA_ROOT, auth_asset.img_large_path))
        else:
            open(os.path.join(MEDIA_ROOT, auth_asset.img_large_path), "wb").write(open(os.path.join(MEDIA_ROOT, auth_asset.res_path), "rb").read())

        if origin_size[0] > 600 or origin_size[1] > 600:
            img.thumbnail((600,600), Image.ANTIALIAS)
            img.save(os.path.join(MEDIA_ROOT, auth_asset.img_medium_path))
        else:
            open(os.path.join(MEDIA_ROOT, auth_asset.img_medium_path), "wb").write(open(os.path.join(MEDIA_ROOT, auth_asset.res_path), "rb").read())

        im_small = ImageOps.fit(img, (240,190), Image.ANTIALIAS)
        im_small.save(os.path.join(MEDIA_ROOT, auth_asset.img_small_path))

        auth_asset.status = 1
        auth_asset.save()
        print 'image .upload  successs..'
        return HttpResponse(SuccessResponse({'id':auth_asset.id, 'title':auth_asset.res_title, 
                                'large':MEDIA_URL + auth_asset.img_large_path,
                                'medium':MEDIA_URL + auth_asset.img_medium_path,
                                'small':MEDIA_URL + auth_asset.img_small_path}))
    elif res_type == "sound":
        auth_asset.res_type = 2 #声音资源
        if ext.lower() not in ALLOWED_SOUND_EXTENSION:
            return HttpResponse(FailResponse(u"只充许上传音频文件(%s)" % ';'.join(ALLOWED_SOUND_EXTENSION)))
        if mem_file.size > ALLOWED_SOUND_UPLOAD_SIZE:
            return HttpResponse(FailResponse(u'文件超过最大充许大小'))

        asset_res_path = "%s/%d" % (get_user_path(request.user, res_type), auth_asset.id)
        asset_res_abspath = os.path.join(MEDIA_ROOT, asset_res_path)
        #创建文件夹
        if not os.path.exists(asset_res_abspath):
            os.makedirs(asset_res_abspath)
        
        auth_asset.origin_path = '%s/origin%s' % (asset_res_path, ext)
        auth_asset.res_path = '%s/%d.mp3' % (asset_res_path, auth_asset.id)
        
        f = open(os.path.join(MEDIA_ROOT, auth_asset.origin_path), "wb")
        # mark: kamihati 2015/4/7  由于本地没有音视频编码服务所以暂时以原文件存储。上线后取消
        f_res = open(os.path.join(MEDIA_ROOT, auth_asset.res_path), "wb")
        for chunk in mem_file.chunks():
            f.write(chunk)
            f_res.write(chunk)
        f.close()
        f_res.close()
        auth_asset.status = 1
        auth_asset.save()
        print 'sound .upload  successs..'
        return HttpResponse(SuccessResponse({'id':auth_asset.id, 'title':auth_asset.res_title, 'url':MEDIA_URL + auth_asset.res_path}))
    elif res_type == "video":
        auth_asset.res_type = 3 #视频资源
        if ext.lower() not in ALLOWED_VIDEO_EXTENSION:
            return HttpResponse(FailResponse(u"只充许上传视频文件(%s)" % ';'.join(ALLOWED_VIDEO_EXTENSION)))
        if mem_file.size > ALLOWED_VIDEO_UPLOAD_SIZE:
            return HttpResponse(FailResponse(u'文件超过最大充许大小'))
        
        asset_res_path = "%s/%d" % (get_user_path(request.user, res_type), auth_asset.id)
        asset_res_abspath = os.path.join(MEDIA_ROOT, asset_res_path)
        #创建文件夹
        if not os.path.exists(asset_res_abspath):
            os.makedirs(asset_res_abspath)
        
        auth_asset.origin_path = '%s/origin%s' % (asset_res_path, ext)
        auth_asset.res_path = '%s/%d.flv' % (asset_res_path, auth_asset.id)
        auth_asset.img_large_path = '%s/l.jpg' % asset_res_path #存视频截图的原图
        auth_asset.img_small_path = '%s/s.jpg' % asset_res_path
        f = open(os.path.join(MEDIA_ROOT, auth_asset.origin_path), "wb")
        for chunk in mem_file.chunks():
            f.write(chunk)
        f.close()
        
        auth_asset.status = 1
        auth_asset.save()
        print 'video .upload  successs..'
        return HttpResponse(SuccessResponse({'id':auth_asset.id, 'title':auth_asset.res_title, 'url':MEDIA_URL + auth_asset.res_path}))
    else:
        return HttpResponse(FailResponse(u'参数错误'))
Пример #29
0
    def __init__(self, prnt, options):
        # Important variables needed throughout the application classes
        self.warn = [] # warnings
        self.bad = [] # errors
        self.errorLog = [] # all errors go here
        self.items = [] # items to rename
        self.spacer = u" " * 6 # spacer for status messages (to clear image)
        # icons used for status bar messages
        self.statusImages = {
            u'failed': wx.Bitmap(utils.icon_path(u'failed_sb.ico'),
                                 wx.BITMAP_TYPE_ICO),
            u'wait': wx.Bitmap(utils.icon_path(u'wait.png'),
                               wx.BITMAP_TYPE_PNG),
            u'warn': wx.Bitmap(utils.icon_path(u'warn_sb.ico'),
                               wx.BITMAP_TYPE_ICO),
            u'complete': wx.Bitmap(utils.icon_path(u'complete.ico'),
                                   wx.BITMAP_TYPE_ICO),
            u'eyes': wx.Bitmap(utils.icon_path(u'eyes.png'),
                               wx.BITMAP_TYPE_PNG),
        }

        app.debug_print("Init MainWindow")
        wx.Frame.__init__(self, id=wxID_MAIN_WINDOW, name=u'MainWindow',
                          parent=prnt, style=wx.DEFAULT_FRAME_STYLE)
        app.debug_print("")

        app.debug_print("======== System Info =======")
        app.debug_print("Operating System: %s - %s - %s" % (platform.system(), platform.release(), platform.version()))
        app.debug_print("Python version: %s" % platform.python_version())
        app.debug_print("wxPython version: %s" % wx.version())
        app.debug_print("============================")
        app.debug_print("")

        # first run?
        utils.init_environment()

        self.set_language()

        # import these modules here since they need language settings activated
        global renamer
        import renamer
        global configs
        import configs
        global picker
        import picker
        global bottomWindow
        import bottomWindow

        # initialize preferences
        app.debug_print("======== Preferences =======")
        app.prefs = preferences.Methods()
        app.debug_print("============================")
        app.debug_print("")

        # build main GUI
        self.__init_ctrls(prnt)

        # clear undo if set in preferences:
        if app.prefs.get(u'clearUndo'):
            try:
                originalFile = codecs.open(utils.get_user_path(u'undo/original.bak'),
                                           'w', "utf-8")
                originalFile.write('')
                renamedFile = codecs.open(utils.get_user_path(u'undo/renamed.bak'),
                                          'w', "utf-8")
                renamedFile.write('')
            except IOError, error:
                utils.make_err_msg(_(u"%s\n\nCould not clear undo") % error,
                                   _(u"Error"))
                pass
Пример #30
0
 def __init__(self, parent):
     self.__init_ctrls(parent)
     self.SetSizerAndFit(self.mainSizer)
     if self.logLocation.GetPath() == '':
         self.logLocation.SetPath(utils.get_user_path('undo'))
Пример #31
0
 def __init__(self, parent):
     self.__init_ctrls(parent)
     self.SetSizerAndFit(self.mainSizer)
     if self.logLocation.GetPath() == '':
         self.logLocation.SetPath(utils.get_user_path('undo'))
Пример #32
0
    def import_items_from_text(self, event):
        """Import item selection from text file."""
        if app.prefs.get('logLocation') != '':
            path = app.prefs.get('logLocation')
        else:
            path = utils.get_user_path(u'undo')

        # settings from preferences
        ext = app.prefs.get('logFextension')
        q = app.prefs.get('logEnclose')
        sep = app.prefs.get('logSeparator')

        wildOnes = _(u"Log file") + u" (*.%s)|*.%s|" % (ext, ext) + \
            _(u"All files") + "(*.*)|*.*"

        # file open dialog
        dlg = wx.FileDialog(
                            self, message=_(u"Import selection from ..."), defaultDir=path,
                            defaultFile=u'', wildcard=wildOnes,
                            style=wx.OPEN | wx.CHANGE_DIR)

        if dlg.ShowModal() == wx.ID_OK:
            original = []
            renamed = []
            unloadbles = ""
            f = dlg.GetPath()

            # undo files have order reversed
            if os.path.basename(f)[0:5] == 'undo_':
                o = 1
                r = 0
            else:
                o = 0
                r = 1
            f = codecs.open(f, 'r', 'utf_8')
            i = 0
            for line in f.readlines():
                i += 1
                line = line.lstrip(q).rstrip(q + '\n').split(q + sep + q)
                # check for existance of every item
                if os.path.exists(line[o]):
                    original.append((line[o], 1))
                    renamed.append([line[r], False])
                else:
                    unloadbles += "%s\n" % line[o]

            # set up for display
            self.toRename = zip(original, renamed)
            self.picker.view.path.SetValue('')
            self.picker.clear_all()

            # only allow rename if there are items
            if len(self.toRename) != i:
                msg = _(u"These items could not be loaded, it doesn't look like they exist :\n\n")
                msg += unloadbles
                dlg = wx.lib.dialogs.ScrolledMessageDialog(self, msg,
                                                           "Could not load all items")
                dlg.ShowModal()
            if len(self.toRename) != 0:
                self.bottomWindow.go.Enable(True)
                self.menuFile.GoMenu.Enable(True)
                self.currentItem = None
                self.display_results(True)
            f.close()
Пример #33
0
    def __init__(self, prnt, options):
        # Important variables needed throughout the application classes
        self.warn = [] # warnings
        self.bad = [] # errors
        self.errorLog = [] # all errors go here
        self.items = [] # items to rename
        self.spacer = u" " * 6 # spacer for status messages (to clear image)
        # icons used for status bar messages
        self.statusImages = {
            u'failed': wx.Bitmap(utils.icon_path(u'failed_sb.ico'),
                                 wx.BITMAP_TYPE_ICO),
            u'wait': wx.Bitmap(utils.icon_path(u'wait.png'),
                               wx.BITMAP_TYPE_PNG),
            u'warn': wx.Bitmap(utils.icon_path(u'warn_sb.ico'),
                               wx.BITMAP_TYPE_ICO),
            u'complete': wx.Bitmap(utils.icon_path(u'complete.ico'),
                                   wx.BITMAP_TYPE_ICO),
            u'eyes': wx.Bitmap(utils.icon_path(u'eyes.png'),
                               wx.BITMAP_TYPE_PNG),
        }

        app.debug_print("Init MainWindow")
        wx.Frame.__init__(self, id=wxID_MAIN_WINDOW, name=u'MainWindow',
                          parent=prnt, style=wx.DEFAULT_FRAME_STYLE)
        app.debug_print("")

        app.debug_print("======== System Info =======")
        app.debug_print("Operating System: %s - %s - %s" % (platform.system(), platform.release(), platform.version()))
        app.debug_print("Python version: %s" % platform.python_version())
        app.debug_print("wxPython version: %s" % wx.version())
        app.debug_print("============================")
        app.debug_print("")

        # first run?
        utils.init_environment()

        self.set_language()

        # import these modules here since they need language settings activated
        global renamer
        import renamer
        global configs
        import configs
        global picker
        import picker
        global bottomWindow
        import bottomWindow

        # initialize preferences
        app.debug_print("======== Preferences =======")
        app.prefs = preferences.Methods()
        app.debug_print("============================")
        app.debug_print("")

        # build main GUI
        self.__init_ctrls(prnt)

        # clear undo if set in preferences:
        if app.prefs.get(u'clearUndo'):
            try:
                originalFile = codecs.open(utils.get_user_path(u'undo/original.bak'),
                                           'w', "utf-8")
                originalFile.write('')
                renamedFile = codecs.open(utils.get_user_path(u'undo/renamed.bak'),
                                          'w', "utf-8")
                renamedFile.write('')
            except IOError, error:
                utils.make_err_msg(_(u"%s\n\nCould not clear undo") % error,
                                   _(u"Error"))
                pass
Пример #34
0
 def __find_pref_file(self):
     prefFile = utils.get_user_path(u'preferences.ini')
     return prefFile
Пример #35
0
    def import_items_from_text(self, event):
        """Import item selection from text file."""
        if app.prefs.get('logLocation') != '':
            path = app.prefs.get('logLocation')
        else:
            path = utils.get_user_path(u'undo')

        # settings from preferences
        ext = app.prefs.get('logFextension')
        q = app.prefs.get('logEnclose')
        sep = app.prefs.get('logSeparator')

        wildOnes = _(u"Log file") + u" (*.%s)|*.%s|" % (ext, ext) + \
            _(u"All files") + "(*.*)|*.*"

        # file open dialog
        dlg = wx.FileDialog(
                            self, message=_(u"Import selection from ..."), defaultDir=path,
                            defaultFile=u'', wildcard=wildOnes,
                            style=wx.OPEN | wx.CHANGE_DIR)

        if dlg.ShowModal() == wx.ID_OK:
            original = []
            renamed = []
            unloadbles = ""
            f = dlg.GetPath()

            # undo files have order reversed
            if os.path.basename(f)[0:5] == 'undo_':
                o = 1
                r = 0
            else:
                o = 0
                r = 1
            f = codecs.open(f, 'r', 'utf_8')
            i = 0
            for line in f.readlines():
                i += 1
                line = line.lstrip(q).rstrip(q + '\n').split(q + sep + q)
                # check for existance of every item
                if os.path.exists(line[o]):
                    original.append((line[o], 1))
                    renamed.append([line[r], False])
                else:
                    unloadbles += "%s\n" % line[o]

            # set up for display
            self.toRename = zip(original, renamed)
            self.picker.view.path.SetValue('')
            self.picker.clear_all()

            # only allow rename if there are items
            if len(self.toRename) != i:
                msg = _(u"These items could not be loaded, it doesn't look like they exist :\n\n")
                msg += unloadbles
                dlg = wx.lib.dialogs.ScrolledMessageDialog(self, msg,
                                                           "Could not load all items")
                dlg.ShowModal()
            if len(self.toRename) != 0:
                self.bottomWindow.go.Enable(True)
                self.menuFile.GoMenu.Enable(True)
                self.currentItem = None
                self.display_results(True)
            f.close()
Пример #36
0
def api_edit_activity_fruit(request):
    '''
    编辑活动作品
    editor: kamihati 2015/4/29  供活动作品管理界面编辑活动作品用
    :param request:
    :return:
    '''
    param = dict()
    id = request.POST.get('id', '')
    param['user_id'] = request.user.id
    param['author_name'] = request.POST.get('author_name')
    param['group_id'] = request.POST.get('group_id')
    param['author_sex'] = int(request.POST.get('author_sex', 0))
    param['author_age'] = int(request.POST.get('author_age', 0))
    param['author_email'] = request.POST.get('author_email', '')
    param['author_telephone'] = request.POST.get('author_telephone', '')
    param['author_address'] = request.POST.get('author_address', '')
    param['school_name'] = request.POST.get('school_name', '')
    param['teacher'] = request.POST.get('teacher', '')
    param['author_brief'] = request.POST.get('author_brief', '')
    param['fruit_brief'] =request.POST.get('fruit_brief', '')
    param['fruit_name'] = request.POST.get('fruit_name')
    activity_id = request.POST.get('activity_id', '')
    fruit_path = request.POST.get('fruit_path', '')
    # 处理上传作品
    if fruit_path != '':
        pass
    # 修改作品信息
    if id not in ('', '0'):
        param['id'] = id
    elif activity_id != '':
        # 新增作品信息
        # 导入获取作品编号的方法
        from activity.fruit_handler import get_fruit_number
        param['number'] = get_fruit_number(activity_id)
        # 导入活动表
        from activity.models import ActivityList
        activity_list = ActivityList.objects.get(pk=activity_id)
        param['fruit_type'] = activity_list.fruit_type
        param['activity_id'] = activity_id
        param['library_id'] = activity_list.library_id
        # 创建用户个人资源
        from diy.models import AuthAsset
        auth_asset = AuthAsset()
        auth_asset.library = request.user.library
        auth_asset.user = request.user
        auth_asset.res_title = param['fruit_name']
        auth_asset.res_type = activity_list.fruit_type
        # 未上传成功前,先状态为-1
        auth_asset.status = -1
        auth_asset.ref_times = 1
        auth_asset.share_times = 1
        auth_asset.save()
        param['auth_asset_id'] = auth_asset.id

        if fruit_path != '':
            import os
            filename, ext = os.path.splitext(fruit_path)
            from utils import get_user_path
            asset_res_path = "%s/%d" % (get_user_path(request.user, auth_asset.res_type), auth_asset.id)
            from WebZone.settings import MEDIA_ROOT
            if not os.path.exists(os.path.join(MEDIA_ROOT, asset_res_path)):
                os.makedirs(os.path.join(MEDIA_ROOT, asset_res_path))
            auth_asset.origin_path = '%s/origin%s' % (asset_res_path, ext)
            auth_asset.res_path = '%s/%d.flv' % (asset_res_path, auth_asset.id)
            auth_asset.img_large_path = '%s/l.jpg' % asset_res_path
            auth_asset.img_small_path = '%s/s.jpg' % asset_res_path
            from utils.decorator import move_temp_file
            move_temp_file(fruit_path, '%s/origin' % asset_res_path)
            auth_asset.status = 1
            auth_asset.save()

    from activity.fruit_handler import edit_activity_fruit
    param['status'] = 2
    fruit = edit_activity_fruit(param)
    if fruit.id is not None:
        return HttpResponse("ok")
    return HttpResponse("fail")