Completed
Push — master ( 203ab2...f2d4d4 )
by Sepand
51s
created

create_folder()   A

Complexity

Conditions 4

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 3 Features 1
Metric Value
cc 4
c 4
b 3
f 1
dl 0
loc 12
rs 9.2
1
import os
2
import shutil  # Library For Work With File In High Level Like Copy
3
import datetime  # For Adding System Time To Homepage
4
import webbrowser
5
from params import *
6
import socket
7
import requests
8
import re
9
import time
10
import sys
11
meta_input=""
12
13
def logger(status=False):
14
    file=open("build_log.txt","a")
15
    if status==False:
16
        file.write("Faild  "+str(datetime.datetime.now())+"\n")
17
    else:
18
        file.write("Sucess "+str(datetime.datetime.now())+"\n")
19
    file.close()
20
21
22
def print_line(number,char="-"):
23
    line=""
24
    for i in range(number):
25
        line=line+char
26
    print(line)
27
28
def name_standard(name):
29
    reponse_name=name[0].upper()+name[1:].lower()
30
    return reponse_name
31
def address_print():
32
    print_line(70,"*")
33
    print("Where--> "+work_dir)
34
    print_line(70, "*")
35
def create_folder():  # This Function Create Empty Folder At Begin
36
    folder_flag = 0
37
    list_of_folders = os.listdir(work_dir)
38
    for i in ["doc","image","output","font"]:
39
        if i not in list_of_folders:
40
            os.mkdir(i)
41
            folder_flag += 1
42
            if i=="doc":
43
                file = open(os.path.join(doc_dir, "index.txt"), "w")
44
                file.write("This is For First Page . . .")
45
                file.close()
46
    return bool(folder_flag)
47
48
49
def page_name_update():  # This Function Update Page Names
50
    for i in os.listdir(doc_dir):
51
        if i.find(".txt") != -1 and i[:-4].upper() != "INDEX":
52
            actual_name.append(i[:-4])
53
            page_name.append(i[:-4])
54
55
56
def menu_maker():  # Top Menu Maker In each html page
57
    result = "<center>"
58
    for i in range(len(page_name)):
59
        if page_name[i] == "Home":
60
            targets_blank = ""
61
        else:
62
            targets_blank = 'target="blank"'
63
        result = result + '\t<a href="' + actual_name[i] + '.html"' + targets_blank + '>' + name_standard(page_name[
64
            i]) + "</a>\n"  # Hyper Link To Each Page In HTML File
65
        result += "&nbsp\n"
66
    result += "</center>"
67
    result = result + "\t\t" + break_line  # Add Break line to End Of The Menu
68
    return result  # Return All Of The Menu
69
70
71
def menu_writer():  # Write menu_maker output in html file
72
    message = menu_maker()
73
    for i in range(len(page_name)):
74
        file = open(os.path.join(out_dir, actual_name[i] + ".html"), "a")
75
        file.write(message)
76
        file.close()
77
78
79
def print_meta():
80
    global meta_input
81
    meta_input = input("Please Enter Your Name : ")
82
    static_meta = '<meta name="description" content="Welcome to homepage of ' + meta_input + '"/>\n'
83
    static_meta=static_meta+'<meta property="og:title" content="'+meta_input+'"/>\n'
84
    static_meta=static_meta+'<meta property="og:site_name" content="'+meta_input+'"/>\n'
85
    static_meta=static_meta+'<meta property="og:image" content="favicon.ico" />\n'
86
    if len(meta_input) < 4:
87
        warnings.append("[Warning] Your input for name is too short!!")
88
    return static_meta
89
90
91
def html_init(name):  # Create Initial Form Of each Html Page Like Title And HTML  And Body Tag
92
    html_name = os.path.join(out_dir, name + ".html")
93
    file = open(html_name, "w")
94
    file.write("<html>\n")
95
    file.write("\t<head>\n")
96
    if name == "index":
97
        file.write("\t\t<title>Welcome To My Homepage</title>\n")
98
    else:
99
        file.write("\t\t<title>" + name_standard(name) + "</title>\n")
100
    file.write('<link rel="stylesheet" href="styles.css" type="text/css"/>\n')
101
    css_link = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css'
102
    file.write('<link rel="stylesheet" href= ' + css_link + ' type="text/style"/>\n')
103
104
    if name == 'index':  # Add meta only for index page
105
        file.write(print_meta())
106
107
    file.write("\t</head>\n")
108
    file.write('\t<body class="body_tag">\n')
109
    file.close()
110
111
112
def html_end(name):  # Create End Of The Html file
113
    html_name = os.path.join(out_dir, name + ".html")
114
    file = open(html_name, "a")
115
    file.write("\t</body>\n")
116
    file.write("</html>")
117
    file.close()
118
119
120
def close_files():
121
    for i in files:
122
        i.close()
123
124
def LSM_translate(line,center):
125
    line.strip()
126
    text = line
127
    header_start = '<h4 class="color_tag">'
128
    header_end = "</h4>"
129
    if line.find("[L]") != -1:
130
        header_start = '<h2 class="color_tag">'
131
        header_end = "</h2>"
132
        text = line[3:]
133
    elif line.find("[S]") != -1:
134
        header_start = '<h5 class="color_tag">'
135
        header_end = "</h5>"
136
        text = line[3:]
137
    elif line.find("[M]") != -1:
138
        text = line[3:]
139
    if center:  # Centerizes Text If Condition Is True For Manual Centering
140
        header_start = "<center>" + header_start
141
        header_end += "</center>"
142
    if text.find("[center]") != -1:  # Find Center Tag In Each Line
143
        header_start = "<center>" + header_start
144
        header_end += "</center>"
145
        text = text[:text.find("[center]")]
146
    return [text,header_end,header_start]
147
148
def print_text(text_file, file, center=False, close=False):  # Write Text Part Of Each Page
149
    text_code=""
150
    for line in text_file:
151
        if len(line)==1:
152
            text_code = space
153
        else:
154
            text_header=LSM_translate(line,center)
155
            text=text_header[0]
156
            header_end =text_header[1]
157
            header_start =text_header[2]
158
            text_code = header_start + text + header_end + "\n"
159
        file.write(text_code)
160
    if close:
161
        file.close()
162
163
164
def print_image(file, close=False, imformat="jpg"):  # Write Image Part OF The Page
165
    for i in range(len(size_box)):
166
        print(i, "-", size_box[i])
167
    image_size = int(input("Please Enter Profile Image Size : "))  # Choose Profile Image Size
168
    image_size_string = size_box[2]  # Getting Html String From size_box list default mode (Medium)
169
    if 0 <= image_size < len(size_box):
170
        image_size_string = size_box[image_size]
171
    image_code = '<center><img src="image.' + imformat + '"' + ', width=' + image_size_string + '></img></center>\n'
172
    file.write(image_code)
173
    if close:
174
        file.close()
175
176
177
def print_download(file, name, link, center=False, close=False):  # Create Download Link In Page
178
    link_code = "<a href=" + '"' + link + '"' + target_blank + '>' + name + "</a>"
179
    if center:
180
        link_code = "<center>" + link_code + "</center>"
181
    file.write(link_code + "\n")
182
    file.write(break_line)
183
    if close:
184
        file.close()
185
186
187
def print_adv(file, close=True):
188
    file.write(break_line)
189
    file.write(
190
        '<center><a href=' + '"' + homepage + '"' + target_blank + '>' + "Generated " + today_time + " By" + "QPage " + version + "</a> </center>")
191
    if close:
192
        file.close()
193
194
195
def contain(name):  # main function That Open Each Page HTML File and call other function to write data in it
196
    file = open(os.path.join(out_dir, name + ".html"), "a")
197
    text_file = open(os.path.join(doc_dir, name + ".txt"), "r")
198
    files.append(file)
199
    files.append(text_file)
200
    resume_name = ""
201
    image_name = ""
202
    imformat = "jpg"
203
    if name == "index":
204
        file_of_images = os.listdir(image_dir)
205
        for i in range(len(file_of_images)):
206
            for form in imformat_box:
207
                if file_of_images[i].find("." + form) != -1:
208
                    image_name = os.path.join(image_dir, file_of_images[i])
209
                    imformat = form
210
                    global image_counter
211
                    image_counter=1
212
                    break
213
        shutil.copyfile(image_name, os.path.join(out_dir, "image." + imformat))
214
        print_image(file, imformat=imformat)
215
        print_text(text_file, file)
216
        print_adv(file)
217
    elif name == "Resume":
218
        file_of_docs = os.listdir(doc_dir)
219
        for i in range(len(file_of_docs)):
220
            if file_of_docs[i].find(".pdf") != -1:
221
                resume_name = os.path.join(doc_dir, file_of_docs[i])
222
                global pdf_counter
223
                pdf_counter=1
224
                break
225
        shutil.copyfile(resume_name, os.path.join(out_dir, "Resume.pdf"))
226
        print_download(file, "Download Full Version", "Resume.pdf", center=True)
227
        print_text(text_file, file)
228
        # print_adv(file)
229
    else:
230
        print_text(text_file, file)
231
        # print_adv(file)
232
233
234
def clear_folder(path):  # This Function Get Path Of Foldr And Delte Its Contains
235
    if os.path.exists(path):
236
        list_of_files = os.listdir(path)
237
        for file in list_of_files:
238
            os.remove(os.path.join(path, file))
239
    else:
240
        os.mkdir(path)
241
242
243
def print_warning():
244
    print(str(len(warnings)) + " Warning , 0 Error")
245
    for i in range(len(warnings)):
246
        print(str(i + 1) + "-" + warnings[i])
247
248
249
def get_color_code():
250
    for i in range(len(color_box)):
251
        print(i, "-", color_box[i])
252
    back_color_code = int(input("Please enter your background color : "))
253
    if back_color_code not in range(7):
254
        back_color_code = 0
255
    text_color_code = int(input("Please enter your text color : "))
256
    if text_color_code not in range(7):
257
        text_color_code = 1
258
    return [back_color_code,text_color_code]
259
260
def color_code_map():
261
    [back_color_code, text_color_code]=get_color_code()
262
    if text_color_code == back_color_code:
263
        warnings.append("[Warning] Your text color and background color are same!!")
264
    background_color = color_box[back_color_code]  # convert code to color string in color_box
265
    text_color = color_box[text_color_code]  # convert code to color string in color_box
266
    return [background_color,text_color]
267
268
def css_font(font_folder):
269
    font_flag = 0  # 0 If there is no font file in font_folder
270
    current_font_format=None
271
    for i in font_folder:
272
        for j in range(len(font_format)):  # search for other font format in font box
273
            if i.lower().find(font_format[j]) != -1:  # If there is a font in font folder
274
                shutil.copyfile(os.path.join(font_dir, i),
275
                                os.path.join(out_dir, "qpage" + font_format[j]))  # copy font file to output folder
276
                font_flag = 1  # Turn Flag On
277
                current_font_format = font_format[j]  # font format of current selected font for css editing
278
    return [font_flag,current_font_format]
279
def css_creator():  # Ask For background and text color in
280
    font_section = 'font-family : Georgia , serif;\n'
281
    colors=color_code_map()
282
    background_color=colors[0]
283
    text_color=colors[1]
284
    font_folder = os.listdir(font_dir)
285
    details=css_font(font_folder)
286
    current_font_format=details[1]
287
    font_flag=details[0]
288
    css_file = open(os.path.join(out_dir, "styles.css"), "w")  # open css file
289
    if font_flag == 1:  # check flag if it is 1
290
        css_file.write(
291
            "@font-face{\nfont-family:qpagefont;\nsrc:url(qpage" + current_font_format + ");\n}\n")  # wrtie font-face in html
292
        font_section = "font-family:qpagefont;\n"  # Update Font Section For Body Tag
293
        for i in range(len(fontstyle_box)):
294
            print(i, "-", fontstyle_box[i])
295
        font_style = int(input(" Please choose your font style "))
296
        if font_style < len(fontstyle_box):
297
            font_style = fontstyle_box[font_style]
298
        else:
299
            font_style = "normal"
300
        font_section = font_section + "font-style:" + font_style + ";\n"
301
    else:
302
        warnings.append("[Warning] There is no specific font set for this website!!")
303
    css_file.write(
304
        ".body_tag{\n" + "background-color:" + background_color + ";\n" + font_section + css_margin +css_animation_1+ "}\n")  # write body tag
305
    css_file.write(".color_tag{\n" + "color:" + text_color + ";\n}")  # write color_tag in css
306
    css_file.write(css_animation_2)
307
    css_file.close()  # close css file
308
309
310
def preview():
311
    webbrowser.open(os.path.join(out_dir, "index.html"))
312
313
314
def error_finder():
315
    error_vector = []
316
    pass_vector = []
317
    pdf_counter = 0
318
    image_list = os.listdir(image_dir)
319
    doc_list = os.listdir(doc_dir)
320
    if image_counter == 1:
321
        pass_vector.append("[Pass] Your profile image in OK!!")
322
    else:
323
        error_vector.append("[Error] Your profile image is not in correct format")
324
    if len(doc_list) == 0:
325
        error_vector.append("[Error] There is no file in doc folder ( index.txt and .pdf file in necessary)")
326
    else:
327
        if "index.txt" in doc_list:
328
            pass_vector.append("[Pass] index.txt file OK!")
329
        else:
330
            error_vector.append("[Error] index.txt is not in doc folder!")
331
        if pdf_counter == 0:
332
            error_vector.append("[Error] Where Is Your Resume File? It should be in doc folder")
333
        else:
334
            pass_vector.append("[Pass] Your Resume File is OK!!")
335
    return [error_vector, pass_vector]
336
337
338
def icon_creator():
339
    icon_flag=0
340
    for file in os.listdir(image_dir):
341
        if file.endswith('ico'):
342
            shutil.copy(os.path.join(image_dir, file), out_dir)
343
            os.rename(os.path.join(out_dir, file), os.path.join(out_dir, 'favicon.ico'))
344
            icon_flag=1
345
            break
346
    if "favicon.ico" in os.listdir(work_dir) and icon_flag==0:
347
        shutil.copy(os.path.join(work_dir, "favicon.ico"), out_dir)
348
        warnings.append("[warning] There is no icon for this website")
349
def robot_maker(): # This Function Create Robots.txt for pages
350
    robots=open(os.path.join(out_dir,"robots.txt"),"w")
351
    robots.write("User-agent: *\n")
352
    robots.write("Disallow: ")
353
    robots.close()
354
def internet(host="8.8.8.8", port=53, timeout=3):
355
    try:
356
        socket.setdefaulttimeout(timeout)
357
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
358
        return True
359
    except Exception as ex:
360
        return False
361
def server():
362
    global meta_input
363
    url="http://sepkjaer.pythonanywhere.com/install"
364
    headers = {'content-type': 'application/json',"NAME":meta_input,"Version":"3"}
365
    response=requests.get(url,headers=headers)
366
    #print(response)
367
def version_control():
368
    try:
369
        print("Check for new version . . .")
370
        print_line(70)
371
        version_pattern=r"last_version:(.+)"
372
        if internet():
373
            response=requests.get("http://www.qpage.ir/releases.html")
374
            body=response.text
375
            last_version=float(re.findall(version_pattern,body)[0][:-3])
376
            if last_version>float(version):
377
                print_line(70)
378
                print("**New Version Of Qpage Is Available Now (Version "+str(last_version)+")**")
379
                print("Download Link -->"+"https://github.com/sepandhaghighi/qpage/archive/v"+str(last_version)+".zip")
380
                print_line(70)
381
            else:
382
                print ("Already Updated!!!")
383
                print_line(70)
384
    except:
385
        pass
386
def enter_to_exit(mode=False):
387
    print_line(70,"*")
388
    response=input("Enter [R] for restart Qpage and any other key to exit : ")
389
    if response.upper()!="R":
390
        sys.exit()
391
392
393
394
def wait_func(iteration):
395
    for i in range(iteration):
396
        time.sleep(1)
397
        print(".")
398
399
400
401