Ejemplo n.º 1
0
 def POST(self): 
     form = config_form()
     result = db.getOAuthConnectionDetails(db.getConn(core.configobj))
     token = result[0]
     secret = result[1]
     smugmug.set_oauth_token(token, secret)
     
     if not form.validates(): 
         return self._GET(smugmug, form, False, form.value['root_dir'],form.value['log_dir'],form.value['data_dir'],form.value['start_time_hour']+':'+form.value['start_time_minute'])
     else:
         try:
             if smugmug.oauth_token == None:
                 smugmug.auth_getAccessToken()
         except smugpy.SmugMugException:
             return self._GET(smugmug, form, True, form.value['root_dir'],form.value['log_dir'],form.value['data_dir'],form.value['start_time_hour']+':'+form.value['start_time_minute'])
         else:
             #self.first = False
             core.configobj.picture_root  = form.value['root_dir']
             core.configobj.log_dir = form.value['log_dir']
             core.configobj.data_dir = form.value['data_dir']
             core.configobj.start_time = form.value['start_time_hour']+':'+form.value['start_time_minute']
             core.configobj.saveConfig()
             myLogger.info("Config file Created.")
             db.initDb(core.configobj)
             myLogger.info("Database started.")
             db.setOAuthConnectionDetails(db.getConn(core.configobj), smugmug.oauth_token, smugmug.oauth_token_secret)
             return self._GET(smugmug, form, False, core.configobj.picture_root, core.configobj.log_dir, core.configobj.data_dir,core.configobj.start_time)
Ejemplo n.º 2
0
 def GET(self):
     form = config_form()
     result = db.getOAuthConnectionDetails(db.getConn(core.configobj))
     token = result[0]
     secret = result[1]
     smugmug.set_oauth_token(token, secret)
     return self._GET(smugmug, form, False, core.configobj.picture_root, core.configobj.log_dir, core.configobj.data_dir,core.configobj.start_time)
Ejemplo n.º 3
0
def upload(configobj, smugmug, lock):
    """
    This method will upload all the missing files 5 at a time.
    """
    myLogger.info("upload() parent process:'{0}' process id:'{1}".format(os.getppid(),os.getpid()))
    start = time.time()
    myLogger.debug('upload - parent process: %s  process id: %s', os.getppid(), os.getpid())
    conn = db.getConn(configobj)
    sync = datetime.now()
    myLogger.debug("getting images to upload")
    uploadImages = db.imagesToUpload(conn)
    myLogger.debug("Have list of images that need to be uploaded.")
    #Loop through the images and download them 
    queue = Queue.Queue()
    #spawn a pool of threads, and pass them queue instance 
    threads = []
    for i in range(3):
        t = UploadThread(queue, conn, configobj, smugmug, lock)
        t.start()
        threads.append(t)
    
    #populate queue with data   
    size = 0
    for uploadImage in uploadImages:
        queue.put(uploadImage)
        size = size + 1
    print size
    
    #wait on the queue until everything has been processed     
    queue.join()    
    
    end = time.time()  
    myLogger.debug("queue emptied in  %d", (end - start))
    #stop the threads 
    myLogger.debug("finished uploading images. it took %d", (end - start))
Ejemplo n.º 4
0
def main():

    movs = [
        join(mFolder, f) for f in listdir(mFolder)
        if isfile(join(mFolder, f)) and 'MP4' in f
    ]
    # movs =[mFolder + 'GP038537.MP4']
    conn = db.getConn(dbase)
    #TODO get list of movies
    # movs = ['/Users/swoolf/GitHub/SoccerHighlights/cv/Videos/180517_v1.MP4','/Users/swoolf/GitHub/SoccerHighlights/cv/Videos/180517_v2.MP4']
    #setUp MT/S3 Clients
    session = boto3.Session()
    client = goal2MT.getClient(session, isLive)
    s3 = boto3.client('s3')

    #Find potential goals and host on S3
    # findGoals.mov2gifs(movs, conn, folder)
    # gifs = db.list_gifs_by_status(conn, 'gif')
    # host.uploadGifs(s3, gifs, bucket)
    #
    # #
    # # #publish to MT
    # goal2MT.urls2MT(client, conn, hostURL, gifs)
    # db.printDB(conn)

    # check MT
    # goal2MT.updateMTanswers(client, conn)
    # db.printDB(conn)

    # compileVideo and post to youTube
    clipsInfo = db.getClips(conn)
    print(clipsInfo)
    movEdit.compileMov('soccerVideo.MP4', clipsInfo)
Ejemplo n.º 5
0
def upload():
    '''adds a post's information into the database'''
    roomCode = request.form.get("rCode")
    roomNum = request.form.get("rNum")
    rating = request.form.get("rating")
    review = request.form.get("review")

    rmID = roomCode + roomNum
    username = session['CAS_USERNAME']
    try:
        postconn = db.getConn(DB)
        uid = db.getUid(postconn, username)
        if db.checkReview(postconn, uid, rmID):
            flash(
                'Already posted a review. Go to your profile to edit your review!'
            )
            return redirect(url_for('index'))
        #upload folder path, and allowed extension of file images
        #check if this exists
        path = 'static/img/{}'.format(username)
        if not os.path.exists(path):
            os.mkdir('static/img/{}'.format(username))
        UPLOAD_FOLDER = 'static/img/{}/'.format(username)
        ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
        app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

        #add code to change file name
        #check allowed files
        def allowed_file(filename):
            return '.' in filename and \
                filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

        uid = db.getUid(postconn, username)
        file = request.files['upload']
        # print("FILE:")
        #print(file)
        if file.filename == '':  #check if they uploaded an img
            filePath = 'NA'
            db.insertReview(postconn, uid, rmID, rating, review, filePath)
            return redirect(url_for('roomReview', rmID=rmID))

        filePath = None
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)  #get the filename
            file.save(os.path.join(
                app.config['UPLOAD_FOLDER'],
                filename))  #save the file to the upload folder destination
            filePath = os.path.join(
                'img/{}/'.format(username), filename
            )  #make a modified path so the profile.html can read it
            db.insertReview(postconn, uid, rmID, rating, review, filePath)
            return redirect(url_for('roomReview', rmID=rmID))

        return redirect(url_for('index'))

    except Exception as err:
        #     print("upload failed because " + str(err))
        flash('Upload failed {why}'.format(why=err))
        return redirect(request.referrer)
Ejemplo n.º 6
0
def insertData(date, cate, title):
    conn = getConn()
    cur = conn.cursor()
    ins_query = 'insert into crowling values({},"{}","{}")'.format(
        date, cate, title)
    cur.execute(ins_query)
    conn.commit()
    conn.close()
Ejemplo n.º 7
0
 def GET(self):
     messages =["Passed along request to upload images."]
     lock = multiprocessing.Lock()
     result = db.getOAuthConnectionDetails(db.getConn(core.configobj))
     token = result[0]
     secret = result[1]
     smugmug.set_oauth_token(token, secret)
     core.smugmugupload.start(smugmug, core.configobj, lock)
     return json.dumps(messages)
Ejemplo n.º 8
0
def create_table():
    conn = getConn()
    cur = conn.cursor()
    cur.execute('''create table crowling(
                                         date int,
                                         category varchar(20),
                                         title varchar(10000)
                                         )''')
    conn.commit()
    conn.close()
Ejemplo n.º 9
0
Archivo: app.py Proyecto: rachn313/feed
def followingList(username):
    '''gets a list of users links that the current profile is following'''
    conn = db.getConn(DB)
    profUID = db.getUid(conn, username)
    users = db.followingUsers(conn, profUID)
    print(users)
    return render_template("listofFollowing.html",
                           page_title="{} Following".format(username),
                           users=users,
                           options=False)
Ejemplo n.º 10
0
 def GET(self):
     lock = multiprocessing.Lock()
     result = db.getOAuthConnectionDetails(db.getConn(core.configobj))
     token = result[0]
     secret = result[1]
     smugmug.set_oauth_token(token, secret)
     core.smugmugscan.start(smugmug, core.configobj, lock)
     web.header('Content-Type', 'application/json')
     messages =["Passed along request to Scan SmugMug."]
     return json.dumps(messages)
Ejemplo n.º 11
0
def sync(configobj, smugmug, lock):
    """
    Does the whole thing, scans, uploads, downloads, etc.  
    """
    myLogger.info("sync() parent process:'{0}' process id:'{1}".format(os.getppid(),os.getpid()))
    
    myLogger.debug('sync - parent process: %s  process id: %s', os.getppid(), os.getpid())
    conn = db.getConn(configobj)
    sync = datetime.now()
    createMissingContainers(conn, smugmug,sync,lock)
Ejemplo n.º 12
0
def createMissingContainers(configobj, smugmug, lock):
    """
    This method will create all the missing Categories, SubCategories and Albums
    that were found locally, but not on SmugMug.
    """
    myLogger.info("createMissingContainers() parent process:'{0}' process id:'{1}".format(os.getppid(),os.getpid()))
    conn = db.getConn(configobj)
    sync = datetime.now()
    createMissingCategories(conn,smugmug, sync, lock)
    createMissingSubCategories(conn,smugmug, sync, lock)
    createMissingAlbums(conn,smugmug, sync, lock)
Ejemplo n.º 13
0
def downloadAndSaveFilmInfo():
    conn = db.getConn()
    all = db.getAllFilmsUrls(conn)
    downloaded = db.getDownloadedFilmsUrls(conn)
    print len(all)
    print len(downloaded)
    for url in all - downloaded:
        soup = filmweb.getFilmSoup(url)
        f = Film(url, soup)
        db.saveFilmInfo(conn, f)
    conn.close()
Ejemplo n.º 14
0
Archivo: app.py Proyecto: rachn313/feed
def likesList(post):
    '''gets the lists of people who liked that particular post '''
    conn = db.getConn(DB)
    #profUID = db.getUid(conn, username)
    pid = post
    userLikesList = db.likesList(conn, pid)
    conn.close()
    return render_template("listofFollowing.html",
                           page_title="Who Likes this post",
                           users=userLikesList,
                           options=False)
Ejemplo n.º 15
0
Archivo: app.py Proyecto: rachn313/feed
def likes(post):
    ''' ajax function that updates the number of likes when either a like is added or deleted'''
    try:
        conn = db.getConn(DB)
        profUID = db.getUid(conn, username)
        numberLikes = db.countLikes(conn, post)
        conn.close()
        return jsonify(numLikes=numberLikes)
    except Exception as err:
        print(err)
        return jsonify({'error': True, 'err': str(err)})
Ejemplo n.º 16
0
Archivo: app.py Proyecto: rachn313/feed
def alikes(post):
    '''ajax function to add a like (insert into database). The number of likes is recalculated and sent through jsonify '''
    try:
        conn = db.getConn(DB)
        db.addLike(conn, post, session['uid'])
        numberLikes = db.countLikes(conn, post)
        conn.close()
        print("here")
        return jsonify(numLikes=numberLikes)
    except Exception as err:
        print(err)
        return jsonify({'error': True, 'err': str(err)})
Ejemplo n.º 17
0
 def __init__(self, queue, conn, configobj, smugmug, lock):
     threading.Thread.__init__(self)
     self._queue = queue
     self._conn = conn
     self._configobj = configobj
     self._lock = lock
     self._smugmug = smugpy.SmugMug(api_key=core.API_KEY, oauth_secret=core.OAUTH_SECRET, api_version="1.3.0", app_name="Smuggler")
     result = db.getOAuthConnectionDetails(db.getConn(self._configobj))
     token = result[0]
     secret = result[1]
     self._smugmug.set_oauth_token(token, secret)
     self._run = True
Ejemplo n.º 18
0
Archivo: app.py Proyecto: rachn313/feed
def dlikes(post):
    ''' ajax function to delete a like (delete into database). The number of likes is recalculated and sent through jsonify'''
    try:
        conn = db.getConn(DB)
        db.removeLike(conn, post, session['uid'])
        numberLikes = db.countLikes(conn, post)
        conn.close()
        print("number of likes after deleting: " + str(numberLikes))
        return jsonify(numLikes=numberLikes)
    except Exception as err:
        print(err)
        return jsonify({'error': True, 'err': str(err)})
Ejemplo n.º 19
0
def Unsave(rmID):
    ''' ajax function for unsaving a room'''
    try:
        username = session['CAS_USERNAME']
        conn = db.getConn(DB)
        uid = db.getUid(conn, username)
        db.removeSave(conn, rmID, uid)
        conn.close()
        return jsonify()
    except Exception as err:
        #print(err)
        return jsonify({'error': True, 'err': str(err)})
Ejemplo n.º 20
0
Archivo: app.py Proyecto: rachn313/feed
def dFollow(username):
    ''' ajax function deletes a follower to the Follows table and updates the follower and following count and returns that as a jsonify '''
    try:
        conn = db.getConn(DB)
        profUID = db.getUid(conn, username)
        db.deletefollower(conn, session['uid'], profUID)
        numFollowing = db.numFollowing(conn, profUID)
        numFollowers = db.numFollowers(conn, profUID)
        return jsonify(updateFollowers=numFollowers,
                       updateFollowing=numFollowing)
    except Exception as err:
        print(err)
        return jsonify({'error': True, 'err': str(err)})
Ejemplo n.º 21
0
Archivo: app.py Proyecto: rachn313/feed
def home():
    '''if the user is not loggin, it will flash and redirect to the appropriate page from the index app route. 
    It will get all the posts, keep track of the username, and gets all the tags. Renders the home.html page'''
    conn = db.getConn(DB)
    # posts = db.getAllPosts(conn)
    if "username" not in session:
        flash("Please log in or sign up to continue")
        return redirect(url_for("index"))
    username = session['username']
    tags = db.getAllTags(conn)

    #change this to AJAX later
    tag = request.values.get('tag')
    sort_by = request.values.get("sort-by")

    conn.close()

    if (tag):
        return redirect(url_for('show_tag_posts', tag=tag))
    else:
        conn = db.getConn(DB)
        if not sort_by:
            sort_by = "recent"  # default sort by recent
        if sort_by == "recent":
            posts = db.getAllPosts(
                conn)  # this is close enough to sort by recent
        elif sort_by == "rating":
            posts = db.getAllPostsSortByRating(conn)
        else:
            posts = None
            flash("need to implement sort by price!!!!")

        return render_template("home.html",
                               page_title="Home • Feed",
                               posts=posts[::-1],
                               username=username,
                               tags=tags,
                               options=True,
                               sort_by=sort_by)
Ejemplo n.º 22
0
Archivo: app.py Proyecto: rachn313/feed
def post(pid):
    ''' gets a single post that is rendered on post.html when clicking on the post in the home feed '''
    conn = db.getConn(DB)
    post = db.getSinglePost(conn, pid)
    likes = db.countLikes(conn, pid)

    if not post:
        flash("Post not found")
        return redirect(request.referrer)

    tags = db.getTagsofPost(conn, pid)
    conn.close()

    rating = post['rating']

    user = None if 'username' not in session else session['username']
    posted = user == post['username']
    conn = db.getConn(DB)
    uid = session['uid']
    conn.close()

    conn = db.getConn(DB)
    liked = db.like_trueFalse(conn, pid, uid)
    conn.close()

    all_tags = []
    if posted:
        all_tags = db.getAllTags(
            db.getConn(DB))  # for displaying tags in edit post

    return render_template("post.html",
                           post=post,
                           pid=pid,
                           tags=tags,
                           posted=posted,
                           all_tags=all_tags,
                           likes=likes,
                           liked=liked)
Ejemplo n.º 23
0
Archivo: app.py Proyecto: rachn313/feed
def delete_post(pid):
    # might be good to check that user deleting post is valid
    # if
    #     flash("post doesn't belong to user logged in")
    try:
        conn = db.getConn(DB)
        db.deletePost(conn, pid)
    except Exception as err:
        flash("error deleting post")
        print("error deleting post")
        return redirect(request.referrer)

    flash("Successfully deleted post")
    return redirect(url_for("home"))
Ejemplo n.º 24
0
def findPictures(configobj, smugmug, lock):
    myLogger.info("findPictures() parent process:'{0}' process id:'{1}".format(os.getppid(),os.getpid()))
    conn = db.getConn(configobj)
    myLogger.info("Starting file scan at => %s", configobj.picture_root)
    _emptyLocalTables(conn, lock)
    now = datetime.datetime.now()
    for root, dirs, files in os.walk(configobj.picture_root):
        for name in files:
            fullname = os.path.join(root, name)
            basename, extension = os.path.splitext(fullname)
            if extension.lower() in core.EXTENSIONS:
                myLogger.debug("FileName: %s", fullname)
                _processFoundFile(conn, configobj.picture_root, fullname, now, lock)
    conn.close()
Ejemplo n.º 25
0
Archivo: app.py Proyecto: rachn313/feed
def sort_rating():

    # better to send posts from ajax over and sort them using python sort
    # or get the posts again from the db sorted by rating?

    # posts = request.form.get("posts")

    query = request.values.get("query")

    if query[:-1] != "null":
        # get posts by query
        conn = db.getConn(DB)
        posts = db.getQueryPostsSortByRating(conn, query[:-1])
    else:
        # get all posts)
        conn = db.getConn(DB)
        posts = db.getAllPostsSortByRating(conn)

    return render_template("home.html",
                           page_title="Results",
                           posts=posts[::-1],
                           options=True,
                           query=query[:-1])
Ejemplo n.º 26
0
Archivo: app.py Proyecto: rachn313/feed
def search():
    '''search by rating or search by time post (most recent) '''
    query = request.values.get('query')

    if query and query[-1] == "/":
        query = query[:-1]  # bad fix

    type_ = request.values.get('type')
    conn = db.getConn(DB)
    if type_ == "posts/": type_ = "posts"  # how to get rid of /?
    if type_ == 'posts':

        # here we also need to check sorting
        sort_by = request.values.get("sort-by")
        if not sort_by:
            sort_by = "recent"
        if sort_by == "recent":
            posts = db.getQueryPosts(conn, query)
        elif sort_by == "rating":
            posts = db.getQueryPostsSortByRating(conn, query)
        else:
            posts = None
            flash("need to implement sort by price!!!!")
        conn.close()
        if not posts:
            flash("no posts found")
        flash("Post results for '{}'".format(query))
        return render_template("home.html",
                               page_title="Results",
                               posts=posts[::-1],
                               options=True,
                               query=query,
                               type=type_,
                               search=True,
                               sort_by=sort_by)
    else:
        # might be nice to have a separate html for users
        users = db.getQueryUsers(conn, query)
        print("type: " + type_)
        conn.close()
        if not users:
            flash("no users found")
        flash("User results for '{}'".format(query))
        return render_template("home.html",
                               page_title="Results",
                               users=users,
                               options=False,
                               query=query,
                               type=type_)
Ejemplo n.º 27
0
def createMissingCategories(configobj, smugmug, lock):
    """
    Will create any missing Categories on SmugMug that have been found locally,
    but not on SmugMug.
    """
    myLogger.debug('createMissingCategories - parent process: %s  process id: %s', os.getppid(), os.getpid())
    conn = db.getConn(configobj)
    sync = datetime.now()
    categories = db.missingSmugMugCategories(conn)
    for category in categories:
        result = smugmug.categories_create(Name=category[0])
        id = result["Category"]["id"]
        myLogger.debug("Category created: '%s' and id '%s'", category[0], id)
        lock.acquire()
        db.insertCategoryLog(conn, id, category[0], sync)
        lock.release()
Ejemplo n.º 28
0
def deleteReview():
    try:
        conn = db.getConn(DB)
        room = request.form.get('rmID')
        username = session['CAS_USERNAME']
        uid = db.getUid(conn, session['CAS_USERNAME'])
        img = db.getImgfromRmID(conn, room)
        #print(imgPath)
        db.deleteReview(conn, uid, room)
        filePath = 'static/{}'.format(img.get('imgPath'))
        os.remove(filePath)
        #print(room, " review deleted")
        return redirect(request.referrer)
    except Exception as err:
        #print(err)
        return (redirect(request.referrer))
Ejemplo n.º 29
0
def roomResults(searched):
    ''' returns a list of shops that serve the searched drink.
    shows address after shop name to avoid confusion with 
    chains of the same name'''
    if 'CAS_USERNAME' in session:
        conn = db.getConn(DB)
        result = db.getSearchedRooms(conn, searched)
        conn.close()
        if (len(searched) <= 4) or (
                not result):  #return list of rooms in that hall or no results.
            return render_template('searchResults.html',
                                   rooms=result,
                                   searched=searched)
        else:
            return redirect(url_for('roomReview', rmID=searched))
    else:  #not logged in:
        return redirect(url_for('index'))
Ejemplo n.º 30
0
Archivo: app.py Proyecto: rachn313/feed
def user(username):
    ''' gets necessary username information '''
    try:
        conn = db.getConn(DB)
        if 'username' in session:
            username = session['username']
            uid = session['uid']
            fullName = session['fullname']
            bioText = db.getBioText(conn, uid)
            profPic = db.getPPic(conn, uid)
            return redirect(url_for('home'))
        else:
            flash('You are not logged in. Please login or join')
            return redirect(url_for('index'))
    except Exception as err:
        flash('some kind of error ' + str(err))
        return redirect(url_for('index'))
Ejemplo n.º 31
0
Archivo: app.py Proyecto: rachn313/feed
def profile(username):
    ''' gets the uid of the profile, sees whether match is true so we know if the its the 
     session's own profile so the edit profile button can appear on their page '''
    conn = db.getConn(DB)
    uid = db.getUid(conn, username)
    #if not uid:
    # flash("User not found")
    # return render_template("home.html")
    uid = uid
    match = False

    if session[
            'uid'] == uid:  #if the session user is on their profile or someone elses
        match = True

    fullName = db.getFullName(conn, uid)
    bioText = db.getBioText(conn, uid)
    profPic = db.getPPic(conn, uid)
    posts = db.getPostsByUser(conn, uid)
    numPosts = db.numPostsUser(conn, uid)
    numFollowing = db.numFollowing(conn, uid)
    numFollowers = db.numFollowers(conn, uid)

    followingBoolean = db.following_trueFalse(
        conn, session['uid'], uid
    )  #note that that a session username cannot follow itself, so jinja2 in profile.page will
    #figure out whether the button should show up using match variable as well, it can carry over but it's used depending on the profile

    if followingBoolean == True:  #checks if there are already following that profile
        buttonText = "Following"
    else:
        buttonText = "Follow"

    return render_template('profile.html',
                           profName=username,
                           uid=uid,
                           fname=fullName['fullname'],
                           bio=bioText['biotxt'],
                           ppic=profPic['profpicPath'],
                           posts=posts,
                           postNum=numPosts,
                           match=match,
                           numFing=numFollowing,
                           numFers=numFollowers,
                           tButton=buttonText)
Ejemplo n.º 32
0
Archivo: app.py Proyecto: rachn313/feed
def upload():
    '''adds a post's information into the database'''
    name = request.form.get("pname")
    restaurant = request.form.get("restaurant")
    location = request.form.get("location")
    rating = request.form.get("rating")
    price = request.form.get("price")
    review = request.form.get("review")
    tags = request.form.getlist("tags")

    uid = session['uid']
    postconn = db.getConn(DB)
    try:
        #add everything but the imgpath to the Post table
        pid = db.insertPost(postconn, uid, name, rating, price, review,
                            restaurant, location)
        f = request.files["upload"]

        ext = f.filename.split('.')[-1]
        filename = secure_filename('{}.{}'.format(pid, ext))
        user_folder = os.path.join(app.config['UPLOADS'], str(uid))

        #if user folder doesn't exist, create it. Otherwise, upload it
        if not (os.path.isdir(user_folder)):
            os.mkdir(user_folder)
        pathname = os.path.join(user_folder, filename)
        f.save(pathname)

        #add the renamed imgpath into the Post table
        filePath = os.path.join('images/{}/'.format(uid), filename)

        db.insertFilepath(postconn, filePath, pid)

        #add to Tagpost table
        for tag in tags:
            tid = db.getTid(postconn, tag)
            db.insertTagPost(postconn, pid, tid)
        flash('Upload successful')
        return redirect(url_for('index'))

    except Exception as err:
        print("upload failed because " + str(err))
        flash('Upload failed {why}'.format(why=err))
        return redirect(url_for('index'))
Ejemplo n.º 33
0
Archivo: app.py Proyecto: rachn313/feed
def show_tag_posts(tag):
    '''displays all posts under the given tag'''
    conn = db.getConn(DB)
    #convert from tag to tid
    tid = db.getTid(conn, tag)['tid']
    #get posts with the tag
    posts = db.getPostsWithTid(conn, tid)
    #check if user is logged in
    if "username" not in session:
        flash("Please log in or sign up to continue")
        return redirect(url_for("index"))
    username = session['username']
    title = "posts under " + tag
    return render_template("home.html",
                           page_title=title,
                           posts=posts,
                           username=username,
                           options=False,
                           tag=tag)
Ejemplo n.º 34
0
def pic():
    conn = db.getConn(DB)
    username = session['CAS_USERNAME']
    uid = db.getUid(conn, username)
    #uid = 1
    #upload folder path, and allowed extension of file images
    #check if this exists
    # username = "******"

    path = 'static/img/{}'.format(username)
    # print(path)
    # print(os.path.exists(path))
    try:
        if not os.path.exists(path):
            os.mkdir('static/img/{}'.format(username))
        UPLOAD_FOLDER = 'static/img/{}/'.format(username)
        ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}
        app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

        #add code to change file name
        #check allowed files
        def allowed_file(filename):
            return '.' in filename and \
                filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

        file = request.files['newpic']
        filePath = None
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)  #get the filename
            file.save(os.path.join(
                app.config['UPLOAD_FOLDER'],
                filename))  #save the file to the upload folder destination
            filePath = os.path.join(
                'img/{}/'.format(username), filename
            )  #make a modified path so the profile.html can read it
            db.changePfp(conn, uid, filePath)
            conn.close()
        conn.close()
        return redirect(request.referrer)
    except Exception as err:
        flash(repr(err))
        return redirect(request.referrer)
Ejemplo n.º 35
0
 def POST(self): 
     form = setup_form()
     if not form.validates(): 
         return self._GET(form, False)
     else:
         try:
             smugmug.auth_getAccessToken()
         except smugpy.SmugMugException:
             return self._GET(form, True)
         else:
             #self.first = False
             core.configobj.picture_root  = form.value['root_dir']
             core.configobj.log_dir = form.value['log_dir']
             core.configobj.data_dir = form.value['data_dir']
             core.configobj.saveConfig()
             myLogger.info("Config file Created.")
             db.initDb(core.configobj)
             myLogger.info("Database started.")
             db.setOAuthConnectionDetails(db.getConn(core.configobj), smugmug.oauth_token, smugmug.oauth_token_secret)
             return web.seeother('/')
Ejemplo n.º 36
0
def getAllPictureInfo(configobj, smugmug, lock):
    myLogger.info("getAllPictures() parent process:'{0}' process id:'{1}".format(os.getppid(),os.getpid()))
    conn = db.getConn(configobj)
    #start fresh on this
    myLogger.debug("Emptying smugmug tables.")
    _emptySmugMugTables(conn, lock)
    
    #now get the albums 
    myLogger.debug("Getting album info from smugmug.")
    albums = _getAlbums(conn, smugmug, lock)
    for album in albums["Albums"]:
        #and the pictures in each album
        myLogger.debug("geting picture info for album '%s'", album["Title"])
        _getPictures(album, conn, smugmug, lock)
    
    #get categories
    ids = _getUserCategories(conn, smugmug, lock)
    _getUserSubCategories(conn, smugmug, lock, ids)
    conn.close()
    myLogger.info('Finished Scanning SmugMug')
Ejemplo n.º 37
0
Archivo: app.py Proyecto: rachn313/feed
def editProf():
    '''gets info from the edit profile form and updates info accordingly '''
    uid = session['uid']
    username = request.form.get('pname')
    print("username " + username)
    fullName = request.form.get('displayName')
    biotext = request.form['bioText']

    conn = db.getConn(DB)

    #upload folder path, and allowed extension of file images
    UPLOAD_FOLDER = 'static/img/{}/'.format(uid)
    ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}
    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

    #check allowed files
    def allowed_file(filename):
        return '.' in filename and \
            filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

    #if 'file' not in request.files:
    #flash('No file part')
    #return redirect('')

    file = request.files['profpic']
    filePath = None
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)  #get the filename
        file.save(os.path.join(
            app.config['UPLOAD_FOLDER'],
            filename))  #save the file to the upload folder destination
        filePath = os.path.join(
            'img/{}/'.format(uid),
            filename)  #make a modified path so the profile.html can read it
        db.updateProfile(conn, uid, username, fullName, biotext,
                         filePath)  #update profile with new pic path
        return redirect(url_for('profile', username=username))
    else:
        #if not pic is uploaded, just upload the pre-filled data
        db.updateProfileNoPic(conn, uid, username, fullName, biotext)
        return redirect(url_for('profile', username=username))
Ejemplo n.º 38
0
Archivo: app.py Proyecto: rachn313/feed
def signUp():
    ''' gets the info from the sign up form and inserts info into the Users table, otherwise if a field is 
    not filled in, will reupload the page for them to try again '''
    if request.method == 'GET':
        return redirect(url_for('index'))
    else:
        try:
            fullname = request.form['fName']
            email = request.form['email']
            username = request.form['username']
            passwd1 = request.form['password1']
            passwd2 = request.form['password2']
            profpicPath = 'img/default_profilepic.jpeg'
            if passwd1 != passwd2:
                flash('passwords do not match')
                return redirect(url_for('index'))
            hashed = bcrypt.hashpw(passwd1.encode('utf-8'), bcrypt.gensalt())
            hashed_str = hashed.decode('utf-8')
            conn = db.getConn(DB)
            curs = dbi.cursor(conn)
            try:
                curs.execute(
                    '''INSERT INTO Users(uid,fullname,email,username,hashed, biotxt, profpicPath)
                                VALUES(null,%s,%s,%s,%s, null, %s)''',
                    [fullname, email, username, hashed_str, profpicPath])
            except Exception as err:
                flash('That username is taken: {}'.format(repr(err)))
                return redirect(url_for('index'))
            curs.execute('select last_insert_id()')
            row = curs.fetchone()
            uid = row[0]
            session['username'] = username
            session['uid'] = uid
            session['logged_in'] = True
            session['fullname'] = fullname

            os.mkdir('static/img/{}'.format(uid))
            return redirect(url_for('user', username=username))
        except Exception as err:
            flash('form submission error: field(s) not filled in ' + str(err))
            return redirect(url_for('index'))
Ejemplo n.º 39
0
def profile():
    if session['CAS_USERNAME']:
        try:
            conn = db.getConn(DB)
            username = session['CAS_USERNAME']
            uid = db.getUid(conn, username)
            rooms = db.getMyRooms(conn, uid)
            path = db.getPicPath(conn, uid)
            savedRooms = db.getSaved(conn, uid)
            conn.close()
            return render_template('profile.html',
                                   page_title='Dormir',
                                   my_rooms=rooms,
                                   pic=path,
                                   username=username,
                                   starred_rooms=savedRooms)
        except Exception as err:
            flash('profile failed to load due to {why}'.format(why=err))
            return redirect(request.referrer)
    else:
        return redirect(url_for('index'))
Ejemplo n.º 40
0
Archivo: app.py Proyecto: rachn313/feed
def login():
    if "username" in session:
        return redirect(url_for("home"))
    if request.method == 'GET':
        return render_template('login.html')
    else:
        try:
            username = request.form['username']
            passwd = request.form['password']
            conn = db.getConn(DB)
            curs = dbi.dictCursor(conn)
            curs.execute(
                '''SELECT *
                        FROM Users
                        WHERE username = %s''', [username])
            row = curs.fetchone()
            if row is None:
                flash(
                    'username and or/password is incorrect. Try again or join'
                )  #making it vague like other social media applications for security precautions
                return redirect(url_for('index'))
            hashed = row['hashed']
            bc = bcrypt.hashpw(passwd.encode('utf-8'), hashed.encode('utf-8'))
            hashed2 = bcrypt.hashpw(passwd.encode('utf-8'),
                                    hashed.encode('utf-8'))
            hashed2_str = hashed2.decode('utf-8')
            if hashed2_str == hashed:
                session['username'] = username
                session['uid'] = row['uid']
                session['logged_in'] = True
                session['fullname'] = row['fullname']
                return redirect(url_for('user', username=username))
            else:
                flash('username and or/password incorrect. Try again or join')
                return redirect(url_for('index'))
        except Exception as err:
            flash('please fill in all fields' + str(err))
            return redirect(url_for('index'))
Ejemplo n.º 41
0
def createMissingAlbums(configobj, smugmug, lock):
    """
    Will create any albums on SmugMug that have been found locally, but not on SmugMug.
    Currently uses the SmugMug defaults for the album properties.
    """
    myLogger.debug('createMissingAlbums - parent process: %s  process id: %s', os.getppid(), os.getpid())
    conn = db.getConn(configobj)
    sync = datetime.now()
    albums = db.missingSmugMugAlbums(conn)
    for album in albums:
        if album[2] == None: #no category or subcategory
            result = smugmug.albums_create(Title=album[0])
        elif album[4] == None: # category but no subcategory
            result = smugmug.albums_create(Title=album[0], CategoryID=album[2])
        else: #has category and subcategory
            result = smugmug.albums_create(Title=album[0], CategoryID=album[2],SubCategoryID=album[4])
        id = result["Album"]["id"]
        key = result["Album"]["Key"]
        myLogger.debug("Album created: '%s' and id '%s' and key '%s'", album[0], id, key)
        lock.acquire()
        db.addSmugAlbum(conn,album[1], album[2], album[3], album[4], album[0], sync, key, id)
        db.insertAlbumLog(conn, id, album[0], album[1], album[3], sync)
        lock.release()
Ejemplo n.º 42
0
def download(configobj, smugmug, lock):
    """
    This method will download all the missing files 5 at a time.
    """
    myLogger.info("download() parent process:'{0}' process id:'{1}".format(os.getppid(),os.getpid()))
    conn = db.getConn(configobj)
    sync = datetime.now()
    myLogger.debug("getting images to download")
    downloadImages = db.imagesToDownload(conn)
    myLogger.debug("Have list of images that need to be downloaded.")
    #Loop through the images and download them 
    queue = Queue.Queue()
    #spawn a pool of threads, and pass them queue instance 
    for i in range(5):
        t = DownloadThread(queue, conn, configobj, smugmug, lock, sync)
        t.start()
    
    #populate queue with data   
    for downloadImage in downloadImages:
        queue.put(downloadImage)
    
    #wait on the queue until everything has been processed     
    queue.join()    
    myLogger.debug("finished downloading images")
Ejemplo n.º 43
0
 def GET(self):
     return pictureReport.findDuplicateSmugMugImageHtml(db.getConn(core.configobj)) 
Ejemplo n.º 44
0
 def GET(self):
     return pictureReport.findMisatchedFilenamesHtml(db.getConn(core.configobj))     
Ejemplo n.º 45
0
 def GET(self):
     return pictureReport.findMismatchedCategoriesHtml(db.getConn(core.configobj))    
Ejemplo n.º 46
0
 def GET(self):
     return pictureReport.findMissingPicturesHtml(db.getConn(core.configobj))     
Ejemplo n.º 47
0
 def GET(self):
     return syncUtil.missingSmugMugSubCategoriesHTML(db.getConn(core.configobj)) 
Ejemplo n.º 48
0
 def GET(self):
     return pictureReport.findMissingSmugMugAlbumsHtml(db.getConn(core.configobj))     
Ejemplo n.º 49
0
def downloadAndSaveFilmHrefs():
    conn = db.getConn()
    alreadySavedUrls = db.getAllFilmsUrls(conn)
    filmweb.downloadFimsFromSearch(int(raw_input('Number of pages to check: ')), int(raw_input('first page: ')), set(alreadySavedUrls), db.filmServerFunc)
    conn.close()
Ejemplo n.º 50
0
 def GET(self):
     return syncUtil.missingSmugMugAlbumsHTML(db.getConn(core.configobj)) 
Ejemplo n.º 51
0
def getAllFilms():
    conn = db.getConn()
    films = db.getAllFilms(conn)
    conn.close()
    return films
Ejemplo n.º 52
0
 def GET(self):
     return syncUtil.missingImagesHTML(db.getConn(core.configobj))