<filename>src/controllers/tasks.py
from src.celery_config import cel
from src.models.models import Sermons, Sermon_Series, Authors, Books_Bible, Congregation
from src.models.db import session
from src.scripts.index import get_env_variable
import configparser as cp
import flask as fl
from datetime import datetime as dt
import time
from src.controllers.index import find_unique_id, strip_extension

@cel.task(bind=True)
def edit_process(self, id, title_given, description, author, date_given, ss, book_bible, chapter_book, cong):
    print("Hello!!")
    self.update_state(state='PROGRESS', meta={'current': 30, 'total': 100, 'status':'Processing'})
    serm = Sermons.query.get(id)

    ss = Sermon_Series.query.get(int(ss))
    #format date!
    date_given = dt.strptime(date_given, '%d-%m-%Y')

    #get the object for the author
    author = Authors.query.get(int(author))

    # get the object for the bible book
    book_bible = Books_Bible.query.get(book_bible)

    # get the cong object
    cong = Congregation.query.get(cong)

    # ensure that the title is unique
    unique = Sermons.query.filter(Sermons.title == title_given).all()

    if len(unique) == 1:
        serm.title = title_given
        serm.date_given = date_given
        serm.description = description
        serm.author = author
        serm.sermon_series = ss
        serm.book_bible = book_bible
        serm.chapter_book = chapter_book
        serm.congregation = cong

        session.add(serm)
        try:
            session.commit()
            self.update_state(state='SUCCESS')
        except KeyError:
            self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Error with database'})
            # return False
    else:
        self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Title already used!'})

@cel.task(bind=True)
def upload_aws(self, filename, title_given, description, author, date_given, fname_thumb, ss, u_id, book_bible, chapter_book, length, cong):
    # init aws platform
    import src.controllers.aws.index as aws
    import os
    from src.controllers.index import produce_feeds

    self.update_state(state='PROGRESS', meta={'current': 5, 'total': 100, 'status':'Verifying uploads'})
    # get the profile name and bucket name from config

    # get conf
    cfg = cp.ConfigParser()
    cfg.read('config.ini')

    bucket_name = cfg['MAIN']['AWS_BUCKET_NAME']
    profile_name = cfg['MAIN']['AWS_PROFILE_NAME']
    a = aws.Aws(profile_name, bucket_name)
    # simpler process for this side of things... just upload directly to the
    # server.

    # check the uploads went to the server
    print("approaching the object head construction stage")
    if a.get_obj_head(filename) and a.get_obj_head(fname_thumb):
        print("object phase is complete")
        self.update_state(state='PROGRESS', meta={'current': 5, 'total': 100, 'status':'Verified. Processing...'})

        date_given = dt.strptime(date_given, '%d-%m-%Y')

        # get the object for the sermon series
        print("initial int is: "+str(ss))
        ss = Sermon_Series.query.get(int(ss))
        print(str(ss))

        #get the object for the author
        author = Authors.query.get(int(author))

        # get the object for the bible book
        book_bible = Books_Bible.query.get(book_bible)

        # get the cong object
        cong = Congregation.query.get(cong)

        # ensure that the title is unique
        unique = Sermons.query.filter(Sermons.title == title_given).all()

        # get the size of the file
        length = a.get_obj_size(filename)

        if len(unique) == 0:
            new_sermon = Sermons(title = title_given, \
                                 date_given = date_given, \
                                 description = description, \
                                 author = author, \
                                 sermon_series = ss, \
                                 aws_key_media = filename, \
                                 aws_key_thumb = fname_thumb, \
                                 book_bible = book_bible, \
                                 chapter_book = chapter_book, \
                                 length = length, \
                                 congregation=cong)

            session.add(new_sermon)
            try:
                session.commit()
                
                self.update_state(state='PROGRESS', meta={'current': 85, 'total': 100, 'status':'Reproducing feeds'})
                
                # reproduce feeds...
                # produce_feeds()
                
                self.update_state(state='SUCCESS')
            except KeyError:
                self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Error with database'})
                # return False
        else:
            self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Failed to upload'})
    else:
        self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Failed to upload'})


@cel.task(bind=True)
def upload_podbean(self, filename, title_given, content_given, date_given, fname_thumb, ss):
    import src.controllers.podbean.index as pod

    # send to podbean now
    client_id = get_env_variable('CLIENT_ID')
    client_sec = get_env_variable('CLIENT_SEC')
    p = pod.init(client_id, client_sec)
    self.update_state(state='PROGRESS', meta={'current': 5, 'total': 100, 'status':'Authenticating with server'})
    res_up = p.auth_upload(filename, "audio/mpeg")
    self.update_state(state='PROGRESS', meta={'current':20, 'total':100, 'status':'Authorising upload'})
    res_up_thumb = p.auth_upload(fname_thumb, "image/png")
    self.update_state(state='PROGRESS', meta={'current':30, 'total':100, 'status':'Authorising upload of image'})
    # deal with the thumbnail first
    if res_up_thumb[0] != False:
        thumb_url = res_up_thumb[0]
        thumb_key = res_up_thumb[1]
        # now upload the img, if there.
        if p.upload_resource(thumb_url, thumb_key, "image/png"):
            self.update_state(state='PROGRESS', meta={'current':40, 'total':100, 'status':'Image uploaded. Publishing'})
        else:
            self.update_state(state='PROGRESS', meta={'current':40, 'total':100, 'status':'Image upload failed. Continuing.'})
    else:
        self.update_state(state='PROGRESS', meta={'current':30, 'total':100, 'status':'Image upload failed. Continuing.'})

    # upload the audio
    if res_up[0] != False:
        url = res_up[0]
        key = res_up[1]
        if p.upload_resource(url, key, "audio/mpeg"):
            self.update_state(state='PROGRESS', meta={'current':70, 'total':100, 'status':'File uploaded. Publishing'})
            res = p.publish_sermon(title_given, content_given, \
            key, thumb_key)
            self.update_state(state='PROGRESS', meta={'current':95, 'total':100, 'status':'Publishing and saving'})
            if res[0] != False:
                # fl.flash("Successfully published sermon!")

                pod_id = res[0]
                pod_media_url = res[1]
                pod_logo_url = res[2]
                # write this to the database

                # get the object for the sermon series
                ss = Sermon_Series.query.get(int(ss))

                # ensure that the title is unique
                unique = Sermons.query.filter(Sermons.title == title_given).all()
                # get the date, format it so it's server ready
                date_given = dt.strptime(date_given, '%d/%m/%Y')
                if len(unique) == 0:
                    new_sermon = Sermons(title=title_given, \
                                         date_given=date_given, \
                                         tmp_media=filename, \
                                         pod_id=pod_id, \
                                         pod_media_url=pod_media_url, \
                                         pod_logo_url=pod_logo_url, \
                                         tmp_thumbnail = fname_thumb, \
                                         sermon_series = ss)
                else:
                    self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Filename not unique'})
                print(title_given, date_given, filename, pod_id, pod_media_url, pod_logo_url, fname_thumb, ss)

                session.add(new_sermon)
                try:
                    session.commit()
                    self.update_state(state='SUCCESS', meta={'current':100, 'total':100, 'status':'Done'})
                except KeyError:
                    self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Error with database'})
                    # return False

                # return True
            else:
                self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Error publishing'})
                # fl.flash("FAILURE to publish")
                # return False
        else:
            self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Error uploading'})
            # fl.flash("FAILURE to upload")
            # return False
    else:
        self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Error authorising upload'})
        # fl.flash("FAILURE to authorise the upload")
        # return False

def t_stat(t_id):
    task = cel.AsyncResult(t_id)
    response = {}
    if task.state != 'PENDING' and task.state != 'FAILURE':
        if task.state == 'SUCCESS':
            response = {
                'state': task.state,
                'current': 100,
                'total':100,
                'status':'Success'
            }
        elif task.state == 'PROGRESS':
            response = {
                'state': task.state,
                'current': task.info['current'],
                'total':100,
                'status':task.info['status']
            }
        else:
            response = {
                'state': task.state,
                'current':0,
                'total':100,
                'status':task.info['status']
                }
    else:
        response = {
        'state': task.state,
        'current': 0,
        'total': 100,
        'status':str(task.info)
        }
    return fl.jsonify(response)

<filename>src/controllers/tasks.py
from src.celery_config import cel
from src.models.models import Sermons, Sermon_Series, Authors, Books_Bible, Congregation
from src.models.db import session
from src.scripts.index import get_env_variable
import configparser as cp
import flask as fl
from datetime import datetime as dt
import time
from src.controllers.index import find_unique_id, strip_extension

@cel.task(bind=True)
def edit_process(self, id, title_given, description, author, date_given, ss, book_bible, chapter_book, cong):
    print("Hello!!")
    self.update_state(state='PROGRESS', meta={'current': 30, 'total': 100, 'status':'Processing'})
    serm = Sermons.query.get(id)

    ss = Sermon_Series.query.get(int(ss))
    #format date!
    date_given = dt.strptime(date_given, '%d-%m-%Y')

    #get the object for the author
    author = Authors.query.get(int(author))

    # get the object for the bible book
    book_bible = Books_Bible.query.get(book_bible)

    # get the cong object
    cong = Congregation.query.get(cong)

    # ensure that the title is unique
    unique = Sermons.query.filter(Sermons.title == title_given).all()

    if len(unique) == 1:
        serm.title = title_given
        serm.date_given = date_given
        serm.description = description
        serm.author = author
        serm.sermon_series = ss
        serm.book_bible = book_bible
        serm.chapter_book = chapter_book
        serm.congregation = cong

        session.add(serm)
        try:
            session.commit()
            self.update_state(state='SUCCESS')
        except KeyError:
            self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Error with database'})
            # return False
    else:
        self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Title already used!'})

@cel.task(bind=True)
def upload_aws(self, filename, title_given, description, author, date_given, fname_thumb, ss, u_id, book_bible, chapter_book, length, cong):
    # init aws platform
    import src.controllers.aws.index as aws
    import os
    from src.controllers.index import produce_feeds

    self.update_state(state='PROGRESS', meta={'current': 5, 'total': 100, 'status':'Verifying uploads'})
    # get the profile name and bucket name from config

    # get conf
    cfg = cp.ConfigParser()
    cfg.read('config.ini')

    bucket_name = cfg['MAIN']['AWS_BUCKET_NAME']
    profile_name = cfg['MAIN']['AWS_PROFILE_NAME']
    a = aws.Aws(profile_name, bucket_name)
    # simpler process for this side of things... just upload directly to the
    # server.

    # check the uploads went to the server
    print("approaching the object head construction stage")
    if a.get_obj_head(filename) and a.get_obj_head(fname_thumb):
        print("object phase is complete")
        self.update_state(state='PROGRESS', meta={'current': 5, 'total': 100, 'status':'Verified. Processing...'})

        date_given = dt.strptime(date_given, '%d-%m-%Y')

        # get the object for the sermon series
        print("initial int is: "+str(ss))
        ss = Sermon_Series.query.get(int(ss))
        print(str(ss))

        #get the object for the author
        author = Authors.query.get(int(author))

        # get the object for the bible book
        book_bible = Books_Bible.query.get(book_bible)

        # get the cong object
        cong = Congregation.query.get(cong)

        # ensure that the title is unique
        unique = Sermons.query.filter(Sermons.title == title_given).all()

        # get the size of the file
        length = a.get_obj_size(filename)

        if len(unique) == 0:
            new_sermon = Sermons(title = title_given, \
                                 date_given = date_given, \
                                 description = description, \
                                 author = author, \
                                 sermon_series = ss, \
                                 aws_key_media = filename, \
                                 aws_key_thumb = fname_thumb, \
                                 book_bible = book_bible, \
                                 chapter_book = chapter_book, \
                                 length = length, \
                                 congregation=cong)

            session.add(new_sermon)
            try:
                session.commit()
                
                self.update_state(state='PROGRESS', meta={'current': 85, 'total': 100, 'status':'Reproducing feeds'})
                
                # reproduce feeds...
                # produce_feeds()
                
                self.update_state(state='SUCCESS')
            except KeyError:
                self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Error with database'})
                # return False
        else:
            self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Failed to upload'})
    else:
        self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Failed to upload'})


@cel.task(bind=True)
def upload_podbean(self, filename, title_given, content_given, date_given, fname_thumb, ss):
    import src.controllers.podbean.index as pod

    # send to podbean now
    client_id = get_env_variable('CLIENT_ID')
    client_sec = get_env_variable('CLIENT_SEC')
    p = pod.init(client_id, client_sec)
    self.update_state(state='PROGRESS', meta={'current': 5, 'total': 100, 'status':'Authenticating with server'})
    res_up = p.auth_upload(filename, "audio/mpeg")
    self.update_state(state='PROGRESS', meta={'current':20, 'total':100, 'status':'Authorising upload'})
    res_up_thumb = p.auth_upload(fname_thumb, "image/png")
    self.update_state(state='PROGRESS', meta={'current':30, 'total':100, 'status':'Authorising upload of image'})
    # deal with the thumbnail first
    if res_up_thumb[0] != False:
        thumb_url = res_up_thumb[0]
        thumb_key = res_up_thumb[1]
        # now upload the img, if there.
        if p.upload_resource(thumb_url, thumb_key, "image/png"):
            self.update_state(state='PROGRESS', meta={'current':40, 'total':100, 'status':'Image uploaded. Publishing'})
        else:
            self.update_state(state='PROGRESS', meta={'current':40, 'total':100, 'status':'Image upload failed. Continuing.'})
    else:
        self.update_state(state='PROGRESS', meta={'current':30, 'total':100, 'status':'Image upload failed. Continuing.'})

    # upload the audio
    if res_up[0] != False:
        url = res_up[0]
        key = res_up[1]
        if p.upload_resource(url, key, "audio/mpeg"):
            self.update_state(state='PROGRESS', meta={'current':70, 'total':100, 'status':'File uploaded. Publishing'})
            res = p.publish_sermon(title_given, content_given, \
            key, thumb_key)
            self.update_state(state='PROGRESS', meta={'current':95, 'total':100, 'status':'Publishing and saving'})
            if res[0] != False:
                # fl.flash("Successfully published sermon!")

                pod_id = res[0]
                pod_media_url = res[1]
                pod_logo_url = res[2]
                # write this to the database

                # get the object for the sermon series
                ss = Sermon_Series.query.get(int(ss))

                # ensure that the title is unique
                unique = Sermons.query.filter(Sermons.title == title_given).all()
                # get the date, format it so it's server ready
                date_given = dt.strptime(date_given, '%d/%m/%Y')
                if len(unique) == 0:
                    new_sermon = Sermons(title=title_given, \
                                         date_given=date_given, \
                                         tmp_media=filename, \
                                         pod_id=pod_id, \
                                         pod_media_url=pod_media_url, \
                                         pod_logo_url=pod_logo_url, \
                                         tmp_thumbnail = fname_thumb, \
                                         sermon_series = ss)
                else:
                    self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Filename not unique'})
                print(title_given, date_given, filename, pod_id, pod_media_url, pod_logo_url, fname_thumb, ss)

                session.add(new_sermon)
                try:
                    session.commit()
                    self.update_state(state='SUCCESS', meta={'current':100, 'total':100, 'status':'Done'})
                except KeyError:
                    self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Error with database'})
                    # return False

                # return True
            else:
                self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Error publishing'})
                # fl.flash("FAILURE to publish")
                # return False
        else:
            self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Error uploading'})
            # fl.flash("FAILURE to upload")
            # return False
    else:
        self.update_state(state='FAILURE', meta={'current':0, 'total':100, 'status':'Error authorising upload'})
        # fl.flash("FAILURE to authorise the upload")
        # return False

def t_stat(t_id):
    task = cel.AsyncResult(t_id)
    response = {}
    if task.state != 'PENDING' and task.state != 'FAILURE':
        if task.state == 'SUCCESS':
            response = {
                'state': task.state,
                'current': 100,
                'total':100,
                'status':'Success'
            }
        elif task.state == 'PROGRESS':
            response = {
                'state': task.state,
                'current': task.info['current'],
                'total':100,
                'status':task.info['status']
            }
        else:
            response = {
                'state': task.state,
                'current':0,
                'total':100,
                'status':task.info['status']
                }
    else:
        response = {
        'state': task.state,
        'current': 0,
        'total': 100,
        'status':str(task.info)
        }
    return fl.jsonify(response)

#format date! #get the object for the author # get the object for the bible book # get the cong object # ensure that the title is unique # return False # init aws platform # get the profile name and bucket name from config # get conf # simpler process for this side of things... just upload directly to the # server. # check the uploads went to the server # get the object for the sermon series #get the object for the author # get the object for the bible book # get the cong object # ensure that the title is unique # get the size of the file # reproduce feeds... # produce_feeds() # return False # send to podbean now # deal with the thumbnail first # now upload the img, if there. # upload the audio # fl.flash("Successfully published sermon!") # write this to the database # get the object for the sermon series # ensure that the title is unique # get the date, format it so it's server ready # return False # return True # fl.flash("FAILURE to publish") # return False # fl.flash("FAILURE to upload") # return False # fl.flash("FAILURE to authorise the upload") # return False