branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>ListlessValkyrie/LVCore<file_sep>/LVCore.Test/TFuse.cs using NUnit.Framework; using System.Threading; using SC = System.ComponentModel; namespace LVCore.Test { [TestFixture] public class TFuse { [Test] [Description("Asserts base behaviour")] public void Fuse_BaseBehaviour() { Fuse fuse = new Fuse(); Assert.IsFalse(fuse.IsBlown); fuse.Blow(); Assert.IsTrue(fuse.IsBlown); } [Test] [Description("Asserts PropertyChanged and Blown events")] public void Fuse_Events() { Fuse fuse = new Fuse(); int propertyChangedEventCount = 0; int blownEventCount = 0; AutoResetEvent timeout = new AutoResetEvent(false); fuse.PropertyChanged += delegate (object sender, SC.PropertyChangedEventArgs e) { if (e.PropertyName == "IsBlown") { Assert.IsTrue(fuse.IsBlown); propertyChangedEventCount++; timeout.Set(); } }; fuse.Blown += delegate () { Assert.IsTrue(fuse.IsBlown); blownEventCount++; }; for (int i = 0; i < 3; i++) { fuse.Blow(); timeout.WaitOne(1000); i++; } Assert.IsTrue(fuse.IsBlown); Assert.IsTrue(propertyChangedEventCount == 1); Assert.IsTrue(blownEventCount == 1); } } }<file_sep>/LVCore/ExtensionMethods/Byte_EM.cs namespace LVCore.ExtensionMethods { public static class Byte_EM { public static string ToHexString(this byte value) { return string.Format("{0:x2}", value); } } } <file_sep>/LVCore.Test/TLVLogging.cs using NUnit.Framework; using NLog; using System.Diagnostics; using LVCore.ExtensionMethods; namespace LVCore.Test { [TestFixture] public class TLVLogging { [Test] public void Logging_BaseTests() { LVLogManager.Instance.SetDebug(); Logger logger = LVLogManager.Instance.GetLogger("TLVLogging_BaseTests"); logger.LogLevelTest(); LVLogManager.Instance.Dispose(); Assert.IsTrue(LVLogManager.Instance.IsDisposed); Process.Start(logger.GetFilePath()); } } } <file_sep>/README.md # LVCore Listless Valkyrie core components <file_sep>/LVCore/ExtensionMethods/Logging_EM.cs using System; using NLog; using NLog.Targets; namespace LVCore.ExtensionMethods { public static class Logger_ExtensionMethods { public static string GetFilePath(this Logger logger) { FileTarget fileTarget = (FileTarget)LogManager.Configuration.FindTargetByName(logger.Name); if (fileTarget != null) { // Need to set timestamp here if filename uses date. // For example - filename="${basedir}/logs/${shortdate}/trace.log" LogEventInfo logEventInfo = new LogEventInfo { TimeStamp = DateTime.Now }; return fileTarget.FileName.Render(logEventInfo); } return default(string); } public static void LogLevelTest(this Logger logger) { logger.Fatal("Fatal log message test"); logger.Error("Error log message test"); logger.Warn("Warn log message test"); logger.Info("Info log message test"); logger.Debug("Debug log message test"); logger.Trace("Trace log message test"); } public static void SetDebug(this LVLogManager logManager) { LVLogManager.Instance.LogLevel = LogLevel.Debug; } } } <file_sep>/LVCore/LVLogManager.cs using System; using System.Collections.Generic; using System.Linq; using NLog; using NLog.Targets; using NLog.Config; using System.IO; namespace LVCore { public class LVLogManager : IDisposable { private Fuse isDisposed = new Fuse(); public bool IsDisposed { get { return isDisposed.IsBlown; } } public void Dispose() { Dispose(true); } private void Dispose(bool isDisposing) { if (isDisposed.IsBlown) { return; } if (isDisposing) { loggers.Clear(); LogManager.Flush(); LogManager.Shutdown(); } isDisposed.Blow(); } private string baseDir = @"C:/temp"; public string BaseDir { get { return baseDir; } } public void SetBaseDir(string folderPath) { if (string.IsNullOrEmpty(folderPath)) { throw new ArgumentNullException("folderPath"); } DirectoryInfo info = new DirectoryInfo(folderPath); if (!info.Exists) { info.Create(); } } private Logger CreateFileLogger(string fileName, string alias) { lock (lockObject) { LoggingConfiguration configuration = LogManager.Configuration == null ? new LoggingConfiguration() : LogManager.Configuration; FileTarget fileTarget = new FileTarget(); configuration.AddTarget(alias, fileTarget); fileTarget.FileName = Path.Combine(BaseDir, fileName); fileTarget.Layout = Layout; LoggingRule rule = new LoggingRule("*", LogLevel, fileTarget); configuration.LoggingRules.Add(rule); LogManager.Configuration = configuration; return LogManager.GetLogger(alias); } } private readonly object lockObject = new object(); private static LVLogManager instance = new LVLogManager(); public static LVLogManager Instance { get { return instance; } } private LVLogManager() { LogManager.Configuration = new LoggingConfiguration(); } ~LVLogManager() { Dispose(false); } private LogLevel logLevel = LogLevel.Info; public LogLevel LogLevel { get { return logLevel; } internal set { if (logLevel != value) { logLevel = value; } } } private string layout = @"${processtime} ${level} ${message}"; public string Layout { get { return layout; } } private List<Logger> loggers = new List<Logger>(); public Logger GetLogger(string name) { if (string.IsNullOrEmpty(name) || IsDisposed) { return null; } name = name.ToLowerInvariant(); lock (lockObject) { Logger logger = loggers.FirstOrDefault(e => e.Name == name); if (logger == null) { logger = CreateFileLogger(name + ".log", name); loggers.Add(logger); return logger; } else { return logger; } } } } } <file_sep>/LVCore/Fuse.cs using System; using System.ComponentModel; using System.Runtime.CompilerServices; namespace LVCore { public sealed class Fuse : INotifyPropertyChanged { private bool isBlown = false; public Fuse() { } public event Action Blown; private void OnBlown() { Action handlers = Blown; if (handlers != null) { foreach (Action handler in handlers.GetInvocationList()) { handler.BeginInvoke(null, null); } } } public string ToFuseString() { return string.Format("{0}", isBlown ? "blown" : "intact"); } public override string ToString() { return ToFuseString(); } public event PropertyChangedEventHandler PropertyChanged; public bool IsBlown { get { return isBlown; } private set { if (value != false && isBlown != value) { isBlown = value; OnBlown(); OnNotifyPropertyChanged(); } } } public void Blow() { IsBlown = true; } private void OnNotifyPropertyChanged([CallerMemberName] String propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
c598e3381a5f0243d578c2a57191d34113f9c2b2
[ "Markdown", "C#" ]
7
C#
ListlessValkyrie/LVCore
21038bf3dfcf215cc7b36919463147af36cdd3a2
d6f0d6f3ee8d17bcaeb2cd3e80d04e0a529785c2
refs/heads/master
<repo_name>HCBLam/LightBnB<file_sep>/1_queries/5_all_my_reservations.sql -- Show all reservations for a user. SELECT reservations.*, properties.*, AVG(rating) AS average_rating FROM reservations JOIN property_reviews ON reservations.id = reservation_id JOIN properties ON properties.id = reservations.property_id WHERE reservations.guest_id = 1 GROUP BY reservations.id, properties.id HAVING end_date < now()::date ORDER BY start_date Limit 10; -- The solution from Compass (note how 2 clauses are attached to WHERE) -- SELECT properties.*, reservations.*, avg(rating) as average_rating -- FROM reservations -- JOIN properties ON reservations.property_id = properties.id -- JOIN property_reviews ON properties.id = property_reviews.property_id -- WHERE reservations.guest_id = 1 -- AND reservations.end_date < now()::date -- GROUP BY properties.id, reservations.id -- ORDER BY reservations.start_date -- LIMIT 10; <file_sep>/seeds/01_seeds.sql INSERT INTO users (id, name, email, password) VALUES (1, '<NAME>', '<EMAIL>', '$2a$10$FB/BOAVhpuLvpOREQVmvmezD4ED/.JBIDRh70tGevYzYzQgFId2u.'), (2, '<NAME>', '<EMAIL>', '$2a$10$FB/BOAVhpuLvpOREQVmvmezD4ED/.JBIDRh70tGevYzYzQgFId2u.'), (3, '<NAME>', '<EMAIL>', '$2a$10$FB/BOAVhpuLvpOREQVmvmezD4ED/.JBIDRh70tGevYzYzQgFId2u.'), (4, '<NAME>', '<EMAIL>', '$2a$10$FB/BOAVhpuLvpOREQVmvmezD4ED/.JBIDRh70tGevYzYzQgFId2u.'), (5, '<NAME>', '<EMAIL>', '$2a$10$FB/BOAVhpuLvpOREQVmvmezD4ED/.JBIDRh70tGevYzYzQgFId2u.'); INSERT INTO properties (id, title, thumbnail_photo_url, cover_photo_url, cost_per_night, parking_spaces, number_of_bathrooms, number_of_bedrooms, country, street, city, province, post_code, active) VALUES (1, 'Pembroke Manor', 'pembroke_url', 'pembroke_cover_url', 25000, 40, 15, 25, 'United Kingdom', 'Pembroke Lane', 'Stratford', 'Stratfordshire', 'A1BX2Y', True), (2, 'Dufferin House', 'dufferin_url', 'dufferin_cover_url', 15000, 30, 10, 20, 'Canada', 'Dufferin Ave', 'Toronto', 'Ontario', 'C3DT4X', True), (3, 'Westbrook Lodge', 'westbrook_url', 'westbrook_cover_url', 10000, 20, 5, 10, 'Canada', 'Grange St', 'Etobicoke', 'Ontario', 'E5FQ6R', True), (4, 'Speed Bump', 'speed_bump_url', 'speed_bump_cover_url', 80000, 20, 7, 12, 'Canada', 'Speed Rd', 'Mississauga', 'Ontario', 'G7HP8O', True), (5, 'Gnome Hole', 'gnome_hole_url', 'gnome_hole_cover_url', 50000, 5, 2, 2, 'Canada', 'Gnome Trail', 'Orangeville', 'Ontario', 'I9JL0M', True); INSERT INTO reservations (id, start_date, end_date, property_id, guest_id) VALUES (1, '2021-01-01', '2021-02-01', 1, 1), (2, '2021-02-01', '2021-03-03', 2, 2), (3, '2021-03-01', '2021-04-04', 3, 3), (4, '2021-04-01', '2021-05-05', 4, 4), (5, '2021-05-01', '2021-06-06', 5, 5); INSERT INTO property_reviews (id, guest_id, property_id, reservation_id, rating, message) VALUES (1, 1, 1, 1, 5, 'Great aristocratic vibes!'), (2, 2, 2, 2, 4, 'Nice colours, very relaxing!'), (3, 3, 3, 3, 3, 'Okay place but the food could be better.'), (4, 4, 4, 4, 2, 'The walls need a new coat of paint.'), (5, 5, 5, 5, 1, 'Worst night of my life!'); <file_sep>/1_queries/4_most_visited_city.sql -- Get a list of the most visited cities. SELECT city, COUNT(reservations.id) AS total_reservation FROM properties JOIN reservations ON properties.id = property_id GROUP BY city ORDER BY total_reservation DESC; <file_sep>/1_queries/1_user_login.sql -- Get details about a single user. SELECT id, name, email, password FROM users WHERE email = '<EMAIL>'; <file_sep>/1_queries/2_avg_length_reservation.sql -- Get the average duration of all reservations. SELECT AVG(end_date - start_date) AS average_duration FROM reservations; <file_sep>/1_queries/3_property_listings_by_city.sql -- Show all details about properties located in Vancouver including their average rating. SELECT properties.*, AVG(rating) AS average_rating FROM properties JOIN property_reviews ON properties.id = property_id WHERE city = 'Vancouver' GROUP BY properties.id HAVING AVG(rating) >= 4 ORDER BY cost_per_night LIMIT 10; -- Solution from Compass (note they include all surrounding areas of Vancouver) -- SELECT properties.*, avg(property_reviews.rating) as average_rating -- FROM properties -- JOIN property_reviews ON properties.id = property_id -- WHERE city LIKE '%ancouv%' -- GROUP BY properties.id -- HAVING avg(property_reviews.rating) >= 4 -- ORDER BY cost_per_night -- LIMIT 10;
12eddcc46e8f8e0ed0d2ac714548ca694a2b2b32
[ "SQL" ]
6
SQL
HCBLam/LightBnB
5f048f7a0864109f452fc07fb0d45b7a09621440
588c29946c701c6d9833ac6ceb9999b3779bf2f1
refs/heads/main
<repo_name>Manasa0108/Passport-Management<file_sep>/admin_complete.py '''executing all the admin table commands''' exec(open('admin_table.py').read()) '''executing the admin login''' exec(open('admin_login.py').read()) <file_sep>/check_status.py from mysql.connector import connect, Error def check_status_func(username, password): try: with connect( host="localhost", user="root", password="<PASSWORD>", database="passport" )as connection: view_records = "SELECT * FROM users" with connection.cursor() as cursor: cursor.execute(view_records) result = cursor.fetchall() except Error as e: print(e) flag = 1 counter = 0 username_local = username password_local = <PASSWORD> for i in result: if i[2] == username_local and i[3] == password_local: flag = 0 break counter += 1 return i[7], i[8],i[9], flag <file_sep>/user_register.py from mysql.connector import connect, Error import uuid def user_register(username, password, email_id, aadhar_card, address, choice): uuid_user = uuid.uuid4() choice_local = choice username_local = username password_local = <PASSWORD> email_id_local = email_id aadhar_card_local = aadhar_card address_local = address status_admin = "pending" status_police = "pending" try: with connect( host="localhost", user="root", password="<PASSWORD>", database="passport" )as connection: view_records = "SELECT * FROM users" with connection.cursor() as cursor: cursor.execute(view_records) result = cursor.fetchall() except Error as e: print(e) exists = 1 for i in result: if i[2] == username_local and i[3] == password_local: exists = 0 break '''adding record to the table''' if exists == 1: try: with connect( host="localhost", user="root", password="<PASSWORD>", database="passport" )as connection: add_records = f"INSERT INTO users(user_id,choice,username,password,email_id,aadhar_card,address,status_admin,status_police) VALUES('{uuid_user}','{choice_local}','{username_local}','{password_local}','{email_id_local}','{aadhar_card_local}','{address_local}','{status_admin}','{status_police}')" with connection.cursor() as cursor: cursor.execute(add_records) connection.commit() return "User added" except Error as e: print(e) else: return "This user alredy exists" <file_sep>/passport.py from flask import Flask, redirect, url_for, render_template, request from police_login import * from admin_login import * from user_register import * from find_user import * from police_verify import * from admin_verify import * from user_login import * from check_status import * from update_date import * app = Flask(__name__) error_code = [] @app.route("/") def hello(): exec(open('setup.py').read()) return redirect(url_for("login")) @app.route("/login", methods=["POST", "GET"]) def login(): if request.form.get('submit_button') == "police": return redirect(url_for("police_login")) elif request.form.get('submit_button') == "admin": return redirect(url_for("admin_login")) elif request.form.get('submit_button') == "user": return redirect(url_for("user_choices")) else: return render_template("index.html") @app.route("/police_login", methods=["POST", "GET"]) def police_login(): if request.method == "GET": return render_template("police_login.html") else: username = request.form.get("username") password = request.form.get("<PASSWORD>") login_status_police = police_login_func(username, password) if login_status_police[1] == 0: return redirect(url_for("police_user_search")) else: error_code.clear() error_code.append("Access Denied") return redirect(url_for("throw_error")) user_details_police = [] @app.route("/police_user_search", methods=["POST", "GET"]) def police_user_search(): if request.method == "GET": return render_template("police_user_search.html") user_details_police.clear() else: user_id_user = request.form.get('user_id') user_exists = find_user(user_id_user) user_details_police.append(user_exists) if user_exists[1] == 0: return redirect(url_for("police_verify")) else: error_code.clear() error_code.append("User does not exist") return redirect(url_for("throw_error")) @app.route("/police_verify", methods=["POST", "GET"]) def police_verify(): if request.method == "GET": return render_template("user_details_display_police.html", user_id=user_details_police[0][0][0], username=user_details_police[0][0][2], address=user_details_police[0][0][6], email=user_details_police[0][0][4], aadhar=user_details_police[0][0][5]) else: if request.form.get('submit_button') == "yes": police_verify_status = police_verify_func(user_details_police[0][0][0]) error_code.clear() error_code.append(police_verify_status[0]) return redirect(url_for("throw_error")) else: error_code.clear() error_code.append("Details not verified") return redirect(url_for("throw_error")) @app.route("/admin_login", methods=["POST", "GET"]) def admin_login(): if request.method == "GET": return render_template("admin_login.html") else: username = request.form.get("username") password = request.form.get("<PASSWORD>") login_status_admin = admin_login_func(username, password) if login_status_admin[1] == 0: return redirect(url_for("admin_user_search")) else: error_code.clear() error_code.append("Access Denied") return redirect(url_for("throw_error")) user_details_admin = [] @app.route("/admin_user_search", methods=["POST", "GET"]) def admin_user_search(): if request.method == "GET": return render_template("admin_user_search.html") user_details_admin.clear() else: user_id_user = request.form.get('user_id') user_exists = find_user(user_id_user) user_details_admin.append(user_exists) if user_exists[1] == 0: return redirect(url_for("admin_verify")) else: error_code.clear() error_code.append("User does not exist") return redirect(url_for("throw_error")) @app.route("/admin_verify", methods=["POST", "GET"]) def admin_verify(): if request.method == "GET": return render_template("user_details_display_admin.html", user_id=user_details_admin[0][0][0], username=user_details_admin[0][0][2], address=user_details_admin[0][0][6], email=user_details_admin[0][0][4], aadhar=user_details_admin[0][0][5]) else: if request.form.get('submit_button') == "yes": admin_verify_status = admin_verify_func(user_details_admin[0][0][0]) return redirect(url_for("issue_date")) else: error_code.clear() error_code.append("Details not verified") return redirect(url_for("throw_error")) @app.route("/issue_date", methods=["POST", "GET"]) def issue_date(): if request.method == "GET": return render_template("appointment.html", admin_status=user_details_admin[0][0][7]) else: issue_date_user = request.form.get('birthday') update_date(user_details_admin[0][0][0], issue_date_user) error_code.clear() error_code.append("Date added") return redirect(url_for("throw_error")) @app.route("/user_choices", methods=["POST", "GET"]) def user_choices(): if request.form.get('submit_button') == "register": return redirect(url_for("user_registration")) elif request.form.get('submit_button') == "check_status": return redirect(url_for("user_login")) else: return render_template("user_options.html") @app.route("/user_login", methods=["POST", "GET"]) def user_login(): if request.method == "GET": return render_template("user_login.html") else: username = request.form.get("username") password = request.form.get("password") login_status_user = user_login_func(username, password) if request.form.get('submit_button') == "proceed": return redirect(url_for("login")) else: if login_status_user[1] == 0: user_status_details = check_status_func(username, password) return render_template("user_status.html", admin_status=user_status_details[0], police_status=user_status_details[1], appointment=user_status_details[2]) else: error_code.clear() error_code.append("Access Denied") return redirect(url_for("throw_error")) @app.route("/user_registration", methods=["POST", "GET"]) def user_registration(): if request.method == "GET": return render_template("user_registration.html") else: username = request.form.get("username") password = <PASSWORD>("<PASSWORD>") email = request.form.get("email") aadhar = request.form.get("aadhar") address = request.form.get("address") choice = request.form.get("reg") registration_status_user = user_register(username, password, email, aadhar, address, choice) error_code.clear() error_code.append(registration_status_user) return redirect(url_for("throw_error")) @app.route("/error_screen", methods=["POST", "GET"]) def throw_error(): if request.method == "GET": return render_template("display_error.html", error=error_code[0]) else: return redirect(url_for("login")) if __name__ == "__main__": app.run(debug=True) <file_sep>/test_db.py from getpass import getpass from mysql.connector import connect, Error try: with connect( host="localhost", user="root", password="<PASSWORD>" ) as connection: create_db_query = "CREATE DATABASE passport" with connection.cursor() as cursor: cursor.execute(create_db_query) except Error as e: print(e) <file_sep>/update_date.py from mysql.connector import connect, Error def update_date(user_id,date): try: with connect( host="localhost", user="root", password="<PASSWORD>", database="passport" )as connection: update_record = f"""UPDATE users SET issue_date='{date}' WHERE user_id='{user_id}'""" with connection.cursor() as cursor: cursor.execute(update_record) connection.commit() except Error as e: print(e)<file_sep>/police_verify.py from mysql.connector import connect, Error def police_verify_func(user_id): try: with connect( host="localhost", user="root", password="<PASSWORD>", database="passport" )as connection: view_records = "SELECT * FROM users" with connection.cursor() as cursor: cursor.execute(view_records) result = cursor.fetchall() except Error as e: print(e) user_id_local = user_id counter = 0 flag = 1 for i in result: if i[0] == user_id_local: flag = 0 break counter += 1 if flag == 1: return "User not found", flag else: try: with connect( host="localhost", user="root", password="<PASSWORD>", database="passport" )as connection: update_record = f"""UPDATE users SET status_police="verified" WHERE user_id='{result[counter][0]}'""" with connection.cursor() as cursor: cursor.execute(update_record) connection.commit() return "Details Verified", flag except Error as e: print(e) else: return "verification has been denied", flag <file_sep>/test_flask.py from flask import Flask, redirect, url_for, render_template, request from police_login import * from admin_login import * from user_register import * app = Flask(__name__) @app.route("/") def hello(): exec(open('setup.py').read()) return redirect(url_for("login")) @app.route("/login", methods=["POST", "GET"]) def login(): if request.form.get('submit_button') == "police": return redirect(url_for("police_login")) elif request.form.get('submit_button') == "admin": return redirect(url_for("admin_login")) elif request.form.get('submit_button') == "user": return redirect(url_for("user_choices")) else: return render_template("index.html") @app.route("/police_login", methods=["POST", "GET"]) def police_login(): if request.method == "GET": return render_template("police_login.html") else: username = request.form.get("username") password = request.form.get("<PASSWORD>") login_status_police = police_login_func(username, password) return f"{login_status_police[0]}" @app.route("/admin_login", methods=["POST", "GET"]) def admin_login(): if request.method == "GET": return render_template("admin_login.html") else: username = request.form.get("username") password = request.form.get("<PASSWORD>") login_status_admin = admin_login_func(username, password) return f"{login_status_admin[0]}" @app.route("/user_choices", methods=["POST", "GET"]) def user_choices(): if request.form.get('submit_button') == "register": return redirect(url_for("user_registration")) elif request.form.get('submit_button') == "check_status": return f"""<html> <link rel="stylesheet" href="/static/style_login_admin.css" type="text/css"> <form action="/admin_login" method="POST"> <div class="login"> <div class="login-screen"> <div class="app-title"> <h1>Admin Login</h1> </div> <div class="login-form"> <div class="control-group"> <input type="text" class="login-field" placeholder="usernmane" name="username"> <label class="login-field-icon fui-user" for="login-name"></label> </div> <div class="control-group"> <input type="password" class="login-field" placeholder="<PASSWORD>" name="password"> <label class="login-field-icon fui-lock" for="login-pass"></label> </div> <input type="submit" value="Log in" class="btn btn-primary btn-large btn-block"> </div> </div> </div> </form> </html> """ else: return render_template("user_options.html") @app.route("/user_registration", methods=["POST", "GET"]) def user_registration(): if request.method == "GET": return render_template("user_registration.html") else: username = request.form.get("username") password = request.form.get("<PASSWORD>") email = request.form.get("email") aadhar = request.form.get("aadhar") address = request.form.get("address") choice = request.form.get("reg") registration_status_user = user_register(username, password, email, aadhar, address, choice) return f"{registration_status_user}" if __name__ == "__main__": app.run(debug=True) <file_sep>/admin_table.py from mysql.connector import connect, Error '''dropping existing table''' try: with connect( host="localhost", user="root", password="<PASSWORD>", database="passport" )as connection: drop_table_query= "DROP TABLE admins" with connection.cursor() as cursor: cursor.execute(drop_table_query) connection.commit() except Error as e: print("1") '''creating the admin table''' try: with connect( host="localhost", user="root", password="<PASSWORD>", database="passport" )as connection: create_table_query = "CREATE TABLE admins(username varchar(10), password varchar(40), city varchar(40) )" with connection.cursor() as cursor: cursor.execute(create_table_query) connection.commit() except Error as e: print("2") '''chceking if table creation is successful''' try: with connect( host="localhost", user="root", password="<PASSWORD>", database="passport" )as connection: show_table="SHOW TABLES" with connection.cursor() as cursor: cursor.execute(show_table) result=cursor.fetchall() print(result) except Error as e: print("3") '''adding records to the table''' try: with connect( host="localhost", user="root", password="<PASSWORD>", database="passport" )as connection: add_records="""INSERT INTO admins(username, password, city) VALUES ("a","a","a"), ("niel","niel","chennai"), ("kshitij","kshitij","delhi"), ("manasa","manasa","hyderabad")""" with connection.cursor() as cursor: cursor.execute(add_records) connection.commit() except Error as e: print("4") '''see the records in the table''' try: with connect( host="localhost", user="root", password="<PASSWORD>", database="passport" )as connection: show_records="SELECT * FROM admins" with connection.cursor() as cursor: cursor.execute(show_records) result=cursor.fetchall() print(result) except Error as e: print("5")<file_sep>/user_table.py from mysql.connector import connect, Error '''dropping existing table''' try: with connect( host="localhost", user="root", password="<PASSWORD>", database="passport" )as connection: drop_table_query= "DROP TABLE users" with connection.cursor() as cursor: cursor.execute(drop_table_query) connection.commit() except Error as e: print(e) '''creating the user table''' try: with connect( host="localhost", user="root", password="<PASSWORD>", database="passport" )as connection: create_table_query = """CREATE TABLE users( user_id varchar(100), choice char(15), username varchar(50), password varchar(50), email_id varchar(70), aadhar_card varchar(10), address varchar(100), status_admin char(10), status_police char(10), issue_date varchar(20))""" with connection.cursor() as cursor: cursor.execute(create_table_query) connection.commit() except Error as e: print(e)<file_sep>/police_complete.py '''executing all the police table commands''' exec(open('police_table.py').read()) '''executing the police login''' exec(open('police_login.py').read()) <file_sep>/check_user.py from mysql.connector import connect, Error '''see the records in the table''' try: with connect( host="localhost", user="root", password="<PASSWORD>", database="passport" )as connection: show_records="SELECT * FROM users" with connection.cursor() as cursor: cursor.execute(show_records) result=cursor.fetchall() for i in result: print(i) except Error as e: print(e)<file_sep>/setup.py '''executing the admin commands''' exec(open('admin_table.py').read()) '''executing the police commands''' exec(open('police_table.py').read()) '''executing the user commands''' exec(open('user_table.py').read()) print("setup complete")<file_sep>/README.md # Passport Management System
82bd11956cd22545d31d1f803cd76a8d3a3201a2
[ "Markdown", "Python" ]
14
Python
Manasa0108/Passport-Management
45c9af0577ea9cbb1196ceef016b1d0443bfc837
8807e4826deef6a80fb8454d7902b3222e1e4d97
refs/heads/main
<file_sep># Importing libraries import PopulateDatabase as pd import createDatabase as cd import validate import NewUI cd.create_database() cd.create_book_table() cd.create_customer_table() cd.create_librarian_table() pd.populate_books() pd.populate_customer() pd.populate_librarian() NewUI.home_page() <file_sep># Mini-Project A python project for a library management connected to a database <file_sep># Importing the necessary libraries import sqlite3 import random # Function to populate the books table with pre existing values if any def populate_books(): connection = sqlite3.connect("Library.db") c = connection.cursor() c.execute("INSERT INTO Book VALUES(1,'For whom the Bell tolls', '<NAME>',10,750);") c.execute("INSERT INTO Book VALUES(2, 'Kurukku', 'Faustima Bama',10,400);") c.execute("INSERT INTO Book VALUES(3,'Shah Nama','Firdausi',5,300);") c.execute("INSERT INTO Book VALUES(4,'The Castle','<NAME>a',7,300);") c.execute("INSERT INTO Book VALUES(5,'Apple Cart','G.B Shaw',4,600);") c.execute("INSERT INTO Book VALUES(6,'Man and Superman','G.B Shaw',7,450);") c.execute("INSERT INTO Book VALUES(7,'All about <NAME>','<NAME>',7,450);") c.execute("INSERT INTO Book VALUES(8,'Arms and the Man','G.b Shaw',3,550);") c.execute("INSERT INTO Book VALUES(9,'Kanterbury Tells','<NAME>',2,480);") c.execute("INSERT INTO Book VALUES(10,'<NAME>','<NAME>',6,550);") c.execute("INSERT INTO Book VALUES(11,'Animal Farm','<NAME>',10,400);") c.execute("INSERT INTO Book VALUES(12,'1984','<NAME>',10,400);") c.execute("INSERT INTO Book VALUES(13,'Tughlaq','Gir<NAME>',13,500);") c.execute("INSERT INTO Book VALUES(14,'faust','Goethe',2,300);") c.execute("INSERT INTO Book VALUES(15,'Paraja','Gopinath Mohanty',2,250);") c.execute("INSERT INTO Book VALUES(16,'She walk,she leads','<NAME>',9,550);") c.execute("INSERT INTO Book VALUES(17,'Asian Drama','<NAME>',3,290);") c.execute("INSERT INTO Book VALUES(18,'A Womans life','Guy de maupassaut',12,400);") c.execute("INSERT INTO Book VALUES(19,'Time Machine','H G Wells',2,200);") c.execute("INSERT INTO Book VALUES(20,'Invisible Man','H G Wells',1,230);") connection.commit() connection.close() # Function to populate the customer table with pre existing values if any def populate_customer(): connection = sqlite3.connect("Library.db") c = connection.cursor() c.execute("INSERT INTO Customer VALUES(1,'John',21,'M','NY','John10');") c.execute("INSERT INTO Customer VALUES(2,'Jay',16,'F','Florida','Jay10');") connection.commit() connection.close() # Function to populate the librarian table with pre existing values if any def populate_librarian(): connection = sqlite3.connect("Library.db") c = connection.cursor() c.execute("INSERT INTO Librarian VALUES(100,'Jess',56,'M','NY','jess10');") c.execute("INSERT INTO Librarian VALUES(101,'Jim',44,'F','Chennai','jim10');") connection.commit() connection.close() # Function to change the librarian password - Invoked from the librarian sign in page def change_librarian_password(name, age, city, password): connection = sqlite3.connect("Library.db") c = connection.cursor() query = "UPDATE Librarian SET Password = '{p}' WHERE Name = '{n}' AND Age = {a} AND City = '{c}';" query = query.format(p=password, n=name, a=age, c=city) c.execute(query) connection.commit() connection.close() # Function to add a new customer to the database def populate_new_customer(name, age, sex, city, password): connection = sqlite3.connect("Library.db") c = connection.cursor() # c.execute("SELECT COUNT(CId), Name FROM Customer;") # variable = c.fetchall() # variable = variable[0][0] + 1 query = "INSERT INTO Customer VALUES({id}, '{n}', {a}, '{s}', '{c}', '{p}');" query = query.format(id=random.randint(1, 30) + random.randint(1, 30), n=name, a=age, s=sex, c=city, p=password) c.execute(query) connection.commit() connection.close() # Function to add a new book to the database def populate_new_book(name, author, qty, price): connection = sqlite3.connect("Library.db") c = connection.cursor() # c.execute("SELECT COUNT(BId), BName FROM Book;") # variable = c.fetchall() # variable = variable[0][0] + 1 query = "INSERT INTO Book VALUES({id}, '{n}', '{a}', {q}, {p});" query = query.format(id=random.randint(1, 30) + random.randint(1, 30), n=name, a=author, q=qty, p=price) c.execute(query) connection.commit() connection.close() # Function to delete a book entirely from the database def delete_from_book(name): connection = sqlite3.connect("Library.db") c = connection.cursor() query = "DELETE FROM Book WHERE BName = '{n}';" query = query.format(n=name) c.execute(query) connection.commit() connection.close() # Function to lend book to a customer def lend_book(name, author, qty): connection = sqlite3.connect("Library.db") c = connection.cursor() query = "SELECT BName, Qty FROM Book WHERE BName = '{n}' AND Author = '{a}';" query = query.format(n=name, a=author) c.execute(query) variable = c.fetchall() variable = variable[0][1] final_qty = variable - qty query1 = "UPDATE Book SET Qty = {q} WHERE BName = '{n}' AND Author = '{a}';" query1 = query1.format(q=final_qty, n=name, a=author) c.execute(query1) connection.commit() connection.close() # Modifying book details def modify_book(name, author, qty, price, ename, eauthor): connection = sqlite3.connect("Library.db") c = connection.cursor() query = """UPDATE Book SET BName = '{n}', Author = '{a}', Qty = {q}, Price = {p} WHERE BName = '{bn}' AND Author = '{ba}';""" query = query.format(n=name, a=author, q=qty, p=price, bn=ename, ba=eauthor) c.execute(query) connection.commit() connection.close() <file_sep># Importing all the required libraries import PySimpleGUI as sg # For Graphical User Interface import validate # Custom Library import PopulateDatabase as pd # Custom Library # This is the User Interface for the Librarian Page def librarian_page(): # Each layout here is a tab in the librarian window tab1_layout = [[sg.Text('Name of the book', grab=True), sg.Input(key='bookname', tooltip='Enter the name of the book')], [sg.Text('Book Author', grab=True), sg.Input(key='author', tooltip='Enter the author of the book')], [sg.Text('Quantity', grab=True), sg.Input(key='qty', tooltip='Enter the number of books you want to buy')], [sg.Text('Price', grab=True), sg.Input(key='price', tooltip='Enter the price of the book')], [sg.Button('Add', key='add'), sg.Button('Cancel', key='cancel')]] tab2_layout = [[sg.Text('Name of the book', grab=True), sg.Input(key='bookname1', tooltip='Enter the book name')], [sg.Text('Author of the book', grab=True), sg.Input(key='author1', tooltip="Enter the author of the book")], [sg.Text('No of books'), sg.Input(key='qty1', tooltip='Enter the number of books')], [sg.Button('Delete', key='delete'), sg.Button('Cancel', key='cancel1')]] tab3_layout = [[sg.Text('Name of the book', grab=True), sg.Input(key='bookname2', tooltip='Enter the book name')], [sg.Text('Author of the book', grab=True), sg.Input(key='author2', tooltip='Enter the author')], [sg.Button('Modify', key='modify'), sg.Button('Cancel', key='cancel2')]] tab4_layout = [[sg.Text('Name of the book', grab=True), sg.Input(key='bookname3', tooltip='Enter the book name')], [sg.Text('Author', grab=True), sg.Input(key='author3', tooltip='Enter the author')], [sg.Text('Number of books', grab=True), sg.Slider(range=(0, 40), orientation='h', key='qty3')], [sg.Button('Lend', key='lend'), sg.Button('Cancel', key='cancel3')]] layout = [[sg.TabGroup([[sg.Tab('Add', tab1_layout), sg.Tab('Delete', tab2_layout), sg.Tab('Modify', tab3_layout), sg.Tab('Lend', tab4_layout)]])]] modify_layout = [[sg.Text('Name', grab=True), sg.Input(key='mname', tooltip='Modified Book Name')], [sg.Text('Author', grab=True), sg.Input(key='mauthor', tooltip='Modified Author')], [sg.Text('Quantity', grab=True), sg.Input(key='mqty', tooltip='Modified quantity')], [sg.Text('Price', grab=True), sg.Input(key='mprice', tooltip='Modified Price')], [sg.Button('Modify', key='m-modify'), sg.Button('Cancel', key='mcancel')]] window = sg.Window('WELCOME', layout) # event loop for the librarian window while True: event, values = window.read() print(event, values) # tab = window.Element('add').GetCurrent() if event in (sg.WIN_CLOSED, 'cancel', 'cancel1', 'cancel2', 'cancel3'): break elif event == 'add': pd.populate_new_book(values['bookname'], values['author'], int(values['qty']), float(values['price'])) break elif event == 'delete': pd.delete_from_book(values['bookname1']) break elif event == 'modify': if validate.book_exists(values['bookname2'], values['author2']): window.close() modification_window = sg.Window('Modify Details', modify_layout) while True: m_event, m_values = modification_window.read() if m_event in (sg.WIN_CLOSED, 'mcancel'): break elif m_event == 'm-modify': pd.modify_book(m_values['mname'], m_values['mauthor'], m_values['mqty'], m_values['mprice'], values['bookname2'], values['author2']) modification_window.close() break modification_window.close() else: sg.Popup('Book does not exist') elif event == 'lend': pd.lend_book(values['bookname3'], values['author3'], int(values['qty3'])) break # Always close the window window.close() # Main page that anyone sees when first opening the application def home_page(): users = ['Librarian', 'Customer'] sex = ['M', 'F', 'O'] sg.theme('DarkBlue3') # Defining each layout before defining the window and the loop for each column main_layout = [[sg.Text('WELCOME', justification='center', size=(80, 2), grab=True)], [sg.Text('Nothing is pleasanter than exploring a library', justification='center', size=(80, 1), grab=True, tooltip='True')], [sg.Text('Are you a Customer or a Librarian? ', grab=True, tooltip='Required')], [sg.R(text, 1, size=(18, 12), auto_size_text=True, tooltip=text, key=text) for text in users], [sg.Button('Confirm', key='mconfirm'), sg.Button('Cancel', key='mcancel')]] customer_layout = [[sg.Frame('Customer Sign In', [[]])], [sg.Text('Name', grab=True, tooltip='Type your name'), sg.Input(key='cname')], [sg.Text('Password', grab=True, tooltip='test'), sg.Input(key='cpass', password_char='*')], [sg.Button('Sign In', key='cconfirm', bind_return_key=True), sg.Button('Exit', key='cexit')], [sg.Text("Don't have an account?"), sg.Button('Sign Up', enable_events=True, key='clink')], [sg.Button('Forgot Password', key='cfpass')]] librarian_layout = [[sg.Frame('Librarian Sign In', [[]])], [sg.Text('Name', grab=True), sg.Input(key='lname', tooltip='Type your name here')], [sg.Text('Password', grab=True), sg.Input(key='lpass', tooltip='Type your password here', password_char='*')], [sg.Button('Sign In', key='lconfirm'), sg.Button('Cancel', key='lcancel')], [sg.Button('Forgot Password', key='libFpass')]] customer_signup_layout = [[sg.Frame('Sign Up', [[]])], [sg.Text('WELCOME', grab=True, justification='center', size=(60, 2))], [sg.Text('Name', grab=True), sg.Input(key='newname', tooltip='Type your name here')], [sg.Text('Age', grab=True), sg.Input(key='newage', tooltip='Type your age here')], [sg.Text('Sex', grab=True)], [sg.R(s, 1, auto_size_text=True, tooltip=s, key=s) for s in sex], [sg.Text('City', grab=True), sg.Input(key='newcity', tooltip='Type your city here')], [sg.Text('Password', grab=True), sg.Input(key='newpass', tooltip='Type your password here', password_char='*')], [sg.Text('Confirm Password', grab=True), sg.Input(key='newpass1', tooltip='Type your password again', password_char='*')], [sg.Button('Create Account', key='create'), sg.Button('Cancel', key='cscancel')]] librarian_forgot_password_layout = [[sg.Frame('Recover', [[]], size=(40, 1))], [sg.Text('Name', grab=True), sg.Input(key='fpname', tooltip='Type your name here')], [sg.Text('Age', grab=True), sg.Input(key='fpage', tooltip='Type your age here')], [sg.Text('Sex', grab=True)], [sg.R(s, 1, auto_size_text=True, tooltip=s, key=s+s) for s in sex], [sg.Text('City', grab=True), sg.Input(key='fpcity', tooltip='Type your city here')], [sg.Button('Find', key='fpfind'), sg.Button('Cancel', key='fpcancel')]] change_librarian_password_layout = [[sg.Text('New Password', grab=True), sg.Input(key='cppass', tooltip='Enter your password', password_char='*')], [sg.Text('Confirm Password', grab=True), sg.Input(key='cppass1', password_char='*', tooltip='Confirm password')], [sg.Button('Confirm', key='cpconfirm'), sg.Button('Cancel', key='cpcancel')]] # librarian_function_layout = [[]] final_layout = [[sg.Column(main_layout, key='layout1'), sg.Column(customer_layout, key='layout2', visible=False), sg.Column(librarian_layout, key='layout3', visible=False), sg.Column(customer_signup_layout, key='layout4', visible=False), sg.Column(librarian_forgot_password_layout, key='layout5', visible=False), sg.Column(change_librarian_password_layout, key='layout6', visible=False)]] window = sg.Window('Welcome to the Library', final_layout) while True: event, values = window.read() if event == 'mcancel' or event == sg.WIN_CLOSED: break elif event == 'mconfirm': if values['Librarian']: window['layout1'].update(visible=False) window['layout3'].update(visible=True) while True: lib_events, lib_values = window.read() if lib_events == 'lcancel' or lib_events == sg.WIN_CLOSED: window['layout3'].update(visible=False) window['layout1'].update(visible=True) break elif lib_events == 'lconfirm': if validate.check_librarian(lib_values['lname'], lib_values['lpass']): # window['layout3'].update(visible=False) # window['layout1'].update(visible=True) window.close() librarian_page() break else: sg.Popup('Librarian not found') window['layout3'].update(visible=False) window['layout3'].update(visible=True) elif lib_events == 'libFpass': window['layout3'].update(visible=False) window['layout5'].update(visible=True) while True: fpevent, fpvalues = window.read() fpvalues['fpage'] = int(fpvalues['fpage']) if fpevent == 'fpcancel' or fpevent == sg.WIN_CLOSED: break elif fpevent == 'fpfind': if validate.find_librarian(fpvalues['fpname'], fpvalues['fpage'], fpvalues['fpcity']): window['layout5'].update(visible=False) window['layout6'].update(visible=True) while True: cpevent, cpvalues = window.read() if cpevent == 'cpcancel' or cpevent == sg.WIN_CLOSED: break elif cpevent == 'cpconfirm': if validate.check_password(cpvalues['cppass'], cpvalues['<PASSWORD>']): pd.change_librarian_password(fpvalues['fpname'], fpvalues['fpage'], fpvalues['fpcity'], cpvalues['cppass']) sg.Popup('Succesfully Changed password') break else: break break else: break break elif values['Customer']: window['layout1'].update(visible=False) window['layout2'].update(visible=True) while True: cusevent, cusvalues = window.read() if cusevent == 'cexit' or cusevent == sg.WIN_CLOSED: break elif cusevent == 'clink': # Sign Up window['layout2'].update(visible=False) window['layout4'].update(visible=True) while True: # Sign Up Event loop csevent, csvalues = window.read() csvalues['newage'] = int(csvalues['newage']) if csevent == 'cscancel' or csevent == sg.WIN_CLOSED: break elif csevent == 'create': if csvalues['M']: if validate.check_password(csvalues['newpass'], csvalues['newpass1']): pd.populate_new_customer(csvalues['newname'], csvalues['newage'], 'M', csvalues['newcity'], csvalues['newpass']) break else: sg.Popup('Password does not match') elif csvalues['F']: if validate.check_password(csvalues['newpass'], csvalues['newpass1']): pd.populate_new_customer(csvalues['newname'], csvalues['newage'], 'F', csvalues['newcity'], csvalues['newpass']) break else: sg.Popup('Password does not match') elif csvalues['O']: if validate.check_password(csvalues['newpass'], csvalues['new<PASSWORD>1']): pd.populate_new_customer(csvalues['newname'], csvalues['newage'], 'O', csvalues['newcity'], csvalues['newpass']) break else: sg.Popup('Password does not match') break window.close() <file_sep> # Importing the PySimpleGUI for simple User Interface to make the application look good # Importing the sqlite3 to maintain the database of the customers and the books import sqlite3 import PySimpleGUI as sg # Function that asks the user whether he/she is a customer or a librarian # This function specifies the window that the user first sees in the application # Write this function later def returning_book(): pass # Write this function later def after_customer_page(): pass # First page you look at this application/ Main page def first_page(): sg.theme('Dark Blue 3') layout = [[sg.Text('Are you a Librarian or a Customer')], [sg.Button('Librarian'), sg.Button('Customer')]] window = sg.Window('Welcome to the Library', layout) event, values = window.read() sg.Popup('Taking you to the ' + event + ' Page') window.close() return event # Creating the required databases for the application # The tables in this database are Customer, Book and Info def creating_database(): conn = sqlite3.connect("Library.db") c = conn.cursor() # Creating a table for the Books available in the library c.execute("""CREATE TABLE IF NOT EXISTS Book( BId INT PRIMARY KEY, BName VARCHAR(50) NOT NULL, Author VARCHAR(50) NOT NULL, Qty INT, Price DOUBLE );""") # A table for the existing customers and their informations c.execute("""CREATE TABLE IF NOT EXISTS Customer( CId INT PRIMARY KEY, Name VARCHAR(50) NOT NULL, Age INT, Password VARCHAR(50));""") # A table for the dates when the books were lent and returned c.execute("""CREATE TABLE IF NOT EXISTS Info( BId INT REFERENCES Book(BId), CId INT REFERENCES Customer(CId), BDate DATE NOT NULL, RDate DATE NOT NULL, Due_Amount DOUBLE );""") # Table for the librarians c.execute("""CREATE TABLE IF NOT EXISTS Librarian( LId INT PRIMARY KEY, Name VARCHAR(50) NOT NULL, Password VARCHAR(50));""") conn.commit() conn.close() # Inserting the necessary values into the table Book def insert_into_books(): conn = sqlite3.connect("Library.db") c = conn.cursor() c.execute("INSERT INTO Book VALUES(1,'For whom the Bell tolls', '<NAME>',10,750);") c.execute("INSERT INTO Book VALUES(2, 'Kurukku', 'Faustima Bama',10,400);") c.execute("INSERT INTO Book VALUES(3,'Shah Nama','Firdausi',5,300);") c.execute("INSERT INTO Book VALUES(4,'The Castle','<NAME>a',7,300);") c.execute("INSERT INTO Book VALUES(5,'Apple Cart','G.B Shaw',4,600);") c.execute("INSERT INTO Book VALUES(6,'Man and Superman','G.B Shaw',7,450);") c.execute("INSERT INTO Book VALUES(7,'All about <NAME>','<NAME>',7,450);") c.execute("INSERT INTO Book VALUES(8,'Arms and the Man','G.b Shaw',3,550);") c.execute("INSERT INTO Book VALUES(9,'Kanterbury Tells','<NAME>',2,480);") c.execute("INSERT INTO Book VALUES(10,'<NAME>','<NAME>',6,550);") c.execute("INSERT INTO Book VALUES(11,'Animal Farm','<NAME>',10,400);") c.execute("INSERT INTO Book VALUES(12,'1984','<NAME>',10,400);") c.execute("INSERT INTO Book VALUES(13,'Tughlaq','Gir<NAME>',13,500);") c.execute("INSERT INTO Book VALUES(14,'faust','Goethe',2,300);") c.execute("INSERT INTO Book VALUES(15,'Paraja','<NAME>',2,250);") c.execute("INSERT INTO Book VALUES(16,'She walk,she leads','<NAME>',9,550);") c.execute("INSERT INTO Book VALUES(17,'Asian Drama','<NAME>',3,290);") c.execute("INSERT INTO Book VALUES(18,'A Womans life','Guy de maupassaut',12,400);") c.execute("INSERT INTO Book VALUES(19,'Time Machine','H G Wells',2,200);") c.execute("INSERT INTO Book VALUES(20,'Invisible Man','H G Wells',1,230);") conn.commit() conn.close() # Inserting into the customers table def insert_into_customers(): conn = sqlite3.connect("Library.db") c = conn.cursor() c.execute("INSERT INTO Customer VALUES(1,'John',21,'john10');") c.execute("INSERT INTO Customer VALUES(2,'Jim',16,'jim10')") conn.commit() conn.close() # Inserting values into the Info table def insert_into_info(): conn = sqlite3.connect("Library.db") c = conn.cursor() c.execute("INSERT INTO Info VALUES(10,1,'20-05-2019','19-07-2019',0);") c.execute("INSERT INTO Info VALUES(17,2,'12-05-2018','25-08-2018',0);") conn.commit() conn.close() # Inserting into the librarian table def insert_into_librarian(): conn = sqlite3.connect("Library.db") c = conn.cursor() c.execute("INSERT INTO Librarian VALUES(1,'Smith,'smith10');") c.execute("INSERT INTO Librarian VALUES(2,'Mark','mark10');") conn.commit() conn.close() # Adding the book into the database - Called by the librarian def add_book_to_database(name, author, qty, price): conn = sqlite3.connect("Library.db") c = conn.cursor() c.execute("SELECT BId FROM Book;") var = len(c.fetchall()) var += 1 query = "INSERT INTO Book VALUES({id}, '{n}', '{a}', {q}, {p});" query = query.format(id=var, n=name, a=author, q=qty, p=price) c.execute(query) conn.commit() conn.close() # Getting the books information as the input form the librarian def add_book(): layout = [[sg.Text('Book Name'), sg.InputText(key='-name-')], [sg.Text('Author of the book'), sg.InputText(key='-author-')], [sg.Text('Number of books'), sg.InputText(key='-qty-')], [sg.Text('Price'), sg.InputText(key='-price-')], [sg.Button('Add')]] window = sg.Window('Welcome', layout) event, values = window.read() add_book_to_database(values['-name-'], values['-author-'], values['-qty-'], values['-price-']) window.close() # Checking if the book exists in the database def check_if_book_exists(name): conn = sqlite3.connect("Library.db") c = conn.cursor() c.execute("SELECT BName, Qty FROM Book;") answer = c.fetchall() conn.commit() conn.close() for i, j in answer: if i == name: return True return False # Checking if number of books entered by the librarian is available def number_of_book(name, number): number = int(number) conn = sqlite3.connect("Library.db") c = conn.cursor() c.execute("SELECT BName, Qty FROM Book;") temporary = c.fetchall() conn.commit() conn.close() for i, j in temporary: if i == name: if number <= int(j): return True return False def delete_book_from_database(name, number): number = int(number) conn = sqlite3.connect("Library.db") c = conn.cursor() c.execute("SELECT BName, Qty FROM Book;") temporary = c.fetchall() conn.commit() conn.close() for i, j in temporary: if i == name: if int(j) == number: conn = sqlite3.connect("Library.db") c = conn.cursor() # query = "DELETE FROM Book WHERE BName = " + name + ";" query = "DELETE FROM Book WHERE BName = '{n}';" query = query.format(n=name) c.execute(query) conn.commit() conn.close() sg.Popup('Record deleted from the database') break else: new_number = int(j) - number conn = sqlite3.connect("Library.db") c = conn.cursor() # querys = "UPDATE Book SET Qty = " + str(new_number) + " WHERE BName = " + name + ";" queries = "UPDATE Book SET Qty = {num} WHERE BName = '{n}';" queries = queries.format(num=new_number, n=name) c.execute(queries) conn.commit() conn.close() sg.Popup('Record altered') break def remove_book(): layout = [[sg.Text('Name of the book you want to remove from the shelf'), sg.InputText(key='-name-')], [sg.Text('Number of books you want to take from the shelf'), sg.Input(key='-number-')], [sg.Button('Delete')]] window = sg.Window('Welcome', layout) event, values = window.read() if event == 'Delete': if check_if_book_exists(values['-name-']): if number_of_book(values['-name-'], values['-number-']): delete_book_from_database(values['-name-'], values['-number-']) else: sg.Popup('Reduce the number of books') window.close() remove_book() else: sg.Popup('Book you entered does not exist in the shelf') window.close() remove_book() window.close() def check_book_name_to_modify(name): conn = sqlite3.connect("Library.db") c = conn.cursor() c.execute("SELECT BName, Qty FROM Book;") temporary = c.fetchall() conn.commit() conn.close() for i, j in temporary: if i == name: return True return False def modify_book_in_database(name): layout = [[sg.Text('Name'), sg.InputText(key='-name-')], [sg.Text('Author'), sg.InputText(key='-author-')], [sg.Text('Qty'), sg.Input(key='-qty-')], [sg.Text('Price'), sg.Input(key='-price-')], [sg.Button('Modify')]] window = sg.Window('Modify what you want to change', layout) event, values = window.read() values['-qty-'] = int(values['-qty-']) values['-price-'] = float(values['-price-']) conn = sqlite3.connect("Library.db") c = conn.cursor() query = "UPDATE BOOK SET BName = '{n}', Author = '{a}', Qty = {q}, Price = {p} WHERE BName = '{na}';" query = query.format(n=values['-name-'], a=values['-author-'], q=values['-qty-'], p=values['-price-'], na=name) c.execute(query) conn.commit() conn.close() window.close() def modify_book(): layout = [[sg.Text('Book you want to modify? '), sg.InputText(key='-name-')], [sg.Button('Modify')]] window = sg.Window('Modify Book', layout) event, values = window.read() if check_book_name_to_modify(values['-name-']): modify_book_in_database(values['-name-']) else: sg.Popup('No record found') window.close() def check_if_existing(name, password): conn = sqlite3.connect("Library.db") c = conn.cursor() c.execute("SELECT Name, Password from Customer;") variable = c.fetchall() conn.commit() conn.close() for i, j in variable: if i == name and j == password: return True return False def get_input(): layout = [[sg.Text('Customer Name'), sg.Input(key='-name-')], [sg.Text('Password'), sg.Input(key='-pass-')], [sg.Button('Check')]] window = sg.Window('Checking Customer', layout) event, values = window.read() window.close() if check_if_existing(values['-name-'], values['-pass-']): return True return False def check_quantity(quantity): conn = sqlite3.connect("Library.db") c = conn.cursor() c.execute("SELECT Quantity, BName FROM Book;") variable = c.fetchall() conn.commit() conn.close() for i, j in variable: if i >= quantity: return True return False def lending_book_details(): layout = [[sg.Text('Name of the book'), sg.Input(key='-name-')], [sg.Text('Author'), sg.Input(key='-author-')], [sg.Text('Quantity'), sg.Input(key='-qty-')], [sg.Button('Lend Book')]] window = sg.Window('Lend Book', layout) event, values = window.read() if check_book_name_to_modify(values['-name-']): if check_quantity(values['-qty-']): pass else: sg.Popup('Not enough books') else: sg.Popup('Book does not exist') def lend_book(): layout = [[sg.Text('Existing Customer')], [sg.Button('Yes'), sg.Button('No')]] window = sg.Window('Customer Verification', layout) event, values = window.read() if event == 'Yes': if get_input(): window.close() lending_book_details() else: window.close() sg.Popup('Customer not in the database') else: window.close() customer_info() def after_librarian(): layout = [[sg.Button('Add a new book to the shelf')], [sg.Button('Remove a book from the shelf')], [sg.Button('Modify book details')], [sg.Button('Lend a book')], [sg.Button('Book return')]] window = sg.Window('Welcome', layout) event, values = window.read() if event == 'Add a new book to the shelf': window.close() add_book() elif event == 'Remove a book from the shelf': window.close() remove_book() elif event == 'Modify book details': window.close() modify_book() elif event == 'Lend a book': window.close() lend_book() else: window.close() returning_book() # Checking for the librarian information def check(name, passw): conn = sqlite3.connect("Library.db") c = conn.cursor() c.execute("SELECT Name, Password FROM Librarian;") var = c.fetchall() conn.commit() conn.close() for i, j in var: if i == name and j == passw: return True return False # This function is called when the user is a librarian def librarian_page(): layout = [[sg.Text('Welcome')], [sg.Text('Name'), sg.InputText(key='-name-')], [sg.Text('Password'), sg.InputText(key='-pass-', password_char='*')], [sg.Button('Sign In')]] window = sg.Window('Librarian Details', layout) event, values = window.read() if check(values['-name-'], values['-pass-']): window.close() after_librarian() else: sg.popup('No such librarian found') window.close() # Checking if the entered information is valid / In the database def check_info(name, password): conn = sqlite3.connect("Library.db") c = conn.cursor() c.execute("SELECT Name,Password FROM Customer;") temporary = c.fetchall() conn.commit() conn.close() for i, j in temporary: if i == name and j == password: return True return False # Shows the customer page def customer_page(): layout = [[sg.Text('Welcome')], [sg.Text('Username: '), sg.InputText(key='-name-')], [sg.Text('Password: '), sg.InputText(key='-password-', password_char='*')], [sg.Button('Sign In')]] window = sg.Window('Customer Details', layout) event, values = window.read() if check_info(values['-name-'], values['-password-']): window.close() after_customer_page() else: window.close() sg.Popup('No such customer found') layout1 = [[sg.Button('Retry')], [sg.Button('Exit')]] window1 = sg.Window('Oops', layout1) event1, values1 = window1.read() if event1 == 'Retry': window1.close() customer_page() else: window1.close() """ def select(): conn = sqlite3.connect("Library.db") c = conn.cursor() c.execute("SELECT Name FROM Customer;") var = c.fetchone() conn.commit() conn.close() print(var) """ # Creating a new customer and inserting the values into the database def create_new_customer(name, age, password): conn = sqlite3.connect("Library.db") c = conn.cursor() c.execute("SELECT CId FROM Customer;") var = c.fetchall() number = len(var) number += 1 query = "INSERT INTO Customer VALUES({num}, '{n}', {a}, '{p}');" query = query.format(num=number, n=name, a=age, p=password) c.execute(query) conn.commit() conn.close() sg.popup('New Customer added to the database') # New Customer Information def customer_info(): layout = [[sg.Text('Name '), sg.InputText(key='-name-')], [sg.Text('Age '), sg.InputText(key='-age-')], [sg.Text('Type your password '), sg.InputText(key='-pass-', password_char='*')], [sg.Text('Confirm your password '), sg.InputText(key='-pass1-', password_char='*')], [sg.Button('Create User')]] window = sg.Window('Welcome!', layout) event, values = window.read() if values['-pass-'] != values['-pass1-']: sg.popup("Password doesn't match ") else: create_new_customer(values['-name-'], values['-age-'], values['-pass-']) window.close() def customer_question(): layout = [[sg.Text('Are you an existing customer?')], [sg.Button('Yes'), sg.Button('No')]] window = sg.Window('Welcome!', layout) event, values = window.read() window.close() if event == 'Yes': customer_page() else: customer_info() """ def choose_next(): layout = [[sg.Button('Add a book', key='-add-')], [sg.Button('Remove a book', key='-remove-')], [sg.Button('Modify book', key='-modify-')]] window = sg.Window('Welcome', layout) event, values = window.read() if event == '-add-': add_book() if event == '-remove-': remove_book() if event == '-modify-': modify_book() window.close() """ """ Function Calls / The main program """ creating_database() insert_into_books() insert_into_customers() insert_into_librarian() insert_into_info() choose = first_page() if choose == 'Librarian': librarian_page() else: customer_question() # select() # choose_next() <file_sep># Importing the libraries import sqlite3 def create_database(): connection = sqlite3.connect("Library.db") connection.close() def create_book_table(): connection = sqlite3.connect("Library.db") c = connection.cursor() c.execute("""CREATE TABLE IF NOT EXISTS Book( BId INT PRIMARY KEY, BName VARCHAR(50) NOT NULL, Author VARCHAR(50) NOT NULL, Qty INT, Price DOUBLE );""") connection.commit() connection.close() def create_customer_table(): connection = sqlite3.connect("Library.db") c = connection.cursor() c.execute("""CREATE TABLE IF NOT EXISTS Customer( CId INT PRIMARY KEY, Name VARCHAR(50) NOT NULL, Age INT, Sex VARCHAR(2), City VARCHAR(20), Password VARCHAR(50));""") connection.commit() connection.close() def create_librarian_table(): connection = sqlite3.connect("Library.db") c = connection.cursor() c.execute("""CREATE TABLE IF NOT EXISTS Librarian( LId INT PRIMARY KEY, Name VARCHAR(50) NOT NULL, Age INT, Sex VARCHAR(2), City VARCHAR(20), Password VARCHAR(50));""") connection.commit() connection.close() <file_sep># Importing the required libraries import sqlite3 def check_customer(name, password): connection = sqlite3.connect("Library.db") c = connection.cursor() c.execute("SELECT Name, Password FROM Customer;") variable = c.fetchall() for i, j in variable: if i == name and j == password: connection.close() return True connection.close() return False def check_librarian(name, password): connection = sqlite3.connect("Library.db") c = connection.cursor() c.execute("SELECT Name, Password FROM Librarian;") variable = c.fetchall() for i, j in variable: if i == name and j == password: connection.close() return True connection.close() return False def book_exists(name, author): connection = sqlite3.connect("Library.db") c = connection.cursor() c.execute("SELECT BName, Author FROM Book;") variable = c.fetchall() for i, j in variable: if i == name and j == author: connection.close() return True connection.close() return False def find_librarian(name, age, city): connection = sqlite3.connect("Library.db") c = connection.cursor() c.execute('SELECT Name, Age, City FROM Librarian;') variable = c.fetchall() connection.commit() connection.close() for i, j, k in variable: if i == name and j == age and k == city: return True return False def check_password(password, cpassword): if password == cpassword: return True return False
b311340bf0830e197e2b966a1c78fde2cc0acb38
[ "Markdown", "Python" ]
7
Python
Gowtham148/Mini-Project
36584bf3be8f105d3d2262746a81d590eea49b3e
c2acdb66f7df8da909b54a1dcc1385dc43ea8448
refs/heads/master
<file_sep>import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Link } from "react-router-dom"; import Home from "./Home/Home"; import About from "./About/About"; import Todos from "./Todos/Todos"; import './App.css'; // import { library } from '@fortawesome/fontawesome-svg-core'; // import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; // import { faEdit } from '@fortawesome/free-solid-svg-icons'; // library.add(faEdit); class App extends Component { render() { return ( <Router> <div className="container"> <ul className="nav"> <li className="nav-item"> <Link className="nav-link active" to="/">Home</Link> </li> <li className="nav-item"> <Link className="nav-link" to="/about/">About</Link> </li> <li className="nav-item"> <Link className="nav-link" to="/todos/">Todos</Link> </li> </ul> <Route path="/" exact component={Home} /> <Route path="/about/" component={About} /> <Route path="/todos/" component={Todos} /> </div> </Router> ); } } export default App; <file_sep>import React, { Component } from 'react'; // import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' class TodoList extends Component { render() { return ( <div className="row"> <ul className="list-group list-group-flush"> {this.props.items.map(item => ( <li className="list-group-item" key={item.id}>{item.text} <i className="fas fa-edit" onClick={this.handleEditTodos.bind(this, item)}></i> </li> ))} </ul> </div> ); } handleEditTodos(item) { this.props.editTodos(item) } } export default TodoList;
2f5e90390191f2a303798deb06cc985c4b5da4d1
[ "JavaScript" ]
2
JavaScript
RealShailender/React-Starter
560319b107ddc7d13684a3f974d21e74b63caba4
f597c3eb6773fd0255a8bae22f4489b524c5f41d
refs/heads/master
<file_sep>Computer Graphics ================= Algorithms for graphics manipulation, used in the Computer Graphics subject. <file_sep>import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import javax.swing.JFrame; import javax.swing.JPanel; /** * Program that draws consecutive lines using Bresenham's algorithm * @author <NAME> */ public class LinesPanel extends JPanel { // Panel's height private int h; // Panel's width private int w; // Space between consecutive lines private int delta; /** * Constructor * @param delta space between consecutive lines */ public LinesPanel(int delta) { super(); this.delta = delta; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Dimension size = getSize(); Insets insets = getInsets(); Graphics2D g2d = (Graphics2D) g; // Sets height and width for current panel w = size.width - insets.left - insets.right; h = size.height - insets.top - insets.bottom; // Set background color g2d.setColor(Color.lightGray); g2d.fillRect(0, 0, w, h); // Draws lines for every pixel g.setColor(Color.red); for (int i = 0; i < w; i++) { drawLine(g2d, i, 0, w, i + 1); } // Draws lines for specified delta g.setColor(Color.blue); for (int i = 0; i < w; i += delta) { drawLine(g2d, i, 0, w, i + 1); } // Draws lines in first and second octant g.setColor(Color.magenta); for(int i = 0; i < 400; i += 10) { drawLine(g2d, 100, 150, 500 - i, 150 + i); } } /** * Draws a point on (x, y) * @param g the Graphics object to draw on * @param x the x-coordinate * @param y the y-coordinate */ public void drawPoint(Graphics g, int x, int y) { // Coordinates must be converted to simulate the Cartesian plane // (the screen's y-coordinate is inverted) g.drawLine(x, h - y, x, h - y); } /** * Draws a line from (x1, y1) to (x2, y2); all values must be positive * @param g the Graphics object to draw on * @param x1 first x-coordinate * @param y1 first y-coordinate * @param x2 second x-coordinate * @param y2 second y-coordinate */ public void drawLine(Graphics g, int x1, int y1, int x2, int y2) { int dy = y2 - y1; int dx = x2 - x1; int inc1, inc2, d; // Check whether the line is in the first or second octant if (dy <= dx) { inc1 = 2 * dy; inc2 = 2 * dy - 2 * dx; d = 2 * dy - dx; for (int x = x1, y = y1; x <= x2; x++) { drawPoint(g, x, y); if (d <= 0) { d += inc1; } else { d += inc2; y++; } } } else { inc1 = 2 * dx; inc2 = 2 * dx - 2 * dy; d = 2 * dx - dy; for (int x = x1, y = y1; y <= y2; y++) { drawPoint(g, x, y); if (d <= 0) { d += inc1; } else { d += inc2; x++; } } } } /** * * @param args first argument can optionally be the delta to use; defaults to 10 */ public static void main(String[] args) { int delta; if (args.length > 0) delta = Integer.parseInt(args[0]); else delta = 10; JFrame frame = new JFrame("Lines"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new LinesPanel(delta)); frame.setSize(800, 600); frame.setLocationRelativeTo(null); frame.setVisible(true); } } <file_sep> import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import javax.swing.JFrame; /** * * @author <NAME> */ public class Main { public static Point[] points; public static boolean[][] lines; public static String[][] transformations; public static void readInput() throws IOException { URL url = Main.class.getResource("input.txt"); BufferedReader br = new BufferedReader(new FileReader(url.getPath())); int numPoints = Integer.parseInt(br.readLine()); points = new Point[numPoints]; lines = new boolean[numPoints][numPoints]; for(int i = 0; i < numPoints; i++) { String[] elements = br.readLine().split(" "); int x = Integer.parseInt(elements[0]), y = Integer.parseInt(elements[1]); points[i] = new Point(x, y); } int numLines = Integer.parseInt(br.readLine()); for (int i = 0; i < numLines; i++) { String[] elements = br.readLine().split(" "); int p1 = Integer.parseInt(elements[0]), p2 = Integer.parseInt(elements[1]); lines[p1][p2] = true; } int numTrans = Integer.parseInt(br.readLine()); transformations = new String[numTrans][3]; for (int i = 0; i < numTrans; i++) { String[] elements = br.readLine().split(" "); transformations[i] = elements.clone(); } } public static void main(String[] args) { try { readInput(); } catch(IOException ioe) { System.out.println("Error reading input file:"); ioe.printStackTrace(); } JFrame mainFrame = new JFrame("Transformations"); mainFrame.setSize(600, 600); mainFrame.add(new DrawPanel()); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setLocationRelativeTo(null); mainFrame.setVisible(true); } } <file_sep> /** * * @author <NAME> */ public class Point { public final double x; public final double y; public Point(double x, double y) { this.x = x; this.y = y; } public Point(double[][] matrix) { x = matrix[0][0]; y = matrix[1][0]; } public double[][] toMatrix() { double[][] matrix = {{x}, {y}, {1}}; return matrix; } public Point add(Point p) { return new Point(x + p.x, y + p.y); } public Point substract(Point p) { return new Point(x - p.x, y - p.y); } public Point[] translateHere(Point[] points) { Point[] centeredPoints = new Point[points.length]; for (int i = 0; i < points.length; i++) { centeredPoints[i] = points[i].substract(this); } return centeredPoints; } public Point[] translateAway(Point[] points) { Point[] restoredPoints = new Point[points.length]; for (int i = 0; i < points.length; i++) { restoredPoints[i] = points[i].add(this); } return restoredPoints; } public static Point getCentroid(Point[] points) { double sumX = 0, sumY = 0; for (int i = 0; i < points.length; i++) { sumX += points[i].x; sumY += points[i].y; } Point p = new Point(sumX / points.length, sumY / points.length); return p; } @Override public String toString() { return "Point(" + x + ", " + y + ")"; } } <file_sep>Transformaciones en 3D ====================== Descripción ----------- Este programa permite hacer transformaciones de rotación, traslación y escalamiento sobre un objeto. Instrucciones ------------- - Traslaciones: Usar las flechas arriba, abajo, izquierda y derecha; para acercar o alejar usar barra espaciadora y enter. - Rotaciones: Usar W y S para rotación sobre el eje X; A y D sobre el eje Y; Q y E sobre el eje Z. - Escalamiento: Usar las teclas + y -. ----------------------- <NAME> Universidad EAFIT 2012<file_sep>Transformaciones ================ Lee una lista de puntos y líneas y aplica transformaciones sobre ellos. El formato para el input es: <num_puntos> x0 y0 x1 y1 <num_lineas> 0 1 1 2 <num_transformaciones> R 90 S 2 T 100 50 Cada línea se indica con dos números, indicando el punto incial y el punto final de acuerdo al orden de entrada. Las transformaciones se indican con una letra inicial seguido de los argumentos, así: R = Rotación, recibe 1 argumento (grados de rotación) T = Traslación, recibe 1 o 2 argumentos, traslación en X y en Y; si es 1 solo argumento se aplica a ambas coordenadas. S = Escalamiento, recibe 1 o 2 argumentos, escalamiento en X y en Y; si es 1 solo argumento se aplica a ambas coordenadas.
52662294fdbc26aae77025c8d77320b543f7e1a8
[ "Markdown", "Java", "Text" ]
6
Markdown
alg0r1thmm/Computer-Graphics
7392dc3ea4c0cd704c79ff36419fddd23a8a1651
85bb14e7bca5eee6ab227f041643b461e2f7c48f
refs/heads/main
<file_sep>package com.hhit.demo.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author wangxiaopeng */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ExceptionCode { int value() default 10000; String message() default "参数校验错误"; } <file_sep>package com.hhit.demo.config; import com.hhit.demo.annotation.ExceptionCode; import com.hhit.demo.enums.ResultCode; import com.hhit.demo.exception.APIException; import com.hhit.demo.vo.ResultVO; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.lang.reflect.Field; /** * @author wangxiaopeng */ @RestControllerAdvice public class ExceptionControllerAdvice { @ExceptionHandler(MethodArgumentNotValidException.class) public ResultVO<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException exception) throws NoSuchFieldException { // 从异常对象中拿到错误信息 String defaultMessage = exception.getBindingResult().getAllErrors().get(0).getDefaultMessage(); // 参数的Class对象,等下好通过字段名称获取Field对象 Class<?> parameterType = exception.getParameter().getParameterType(); // 拿到错误的字段名称 String fieldName = exception.getBindingResult().getFieldError().getField(); Field field = parameterType.getDeclaredField(fieldName); // 获取Field对象上的自定义注解 ExceptionCode annotation = field.getAnnotation(ExceptionCode.class); // 有注解的话就返回注解的响应信息 if (annotation != null) { return new ResultVO<>(annotation.value(), annotation.message(), defaultMessage); } // 没有注解就提取错误提示信息进行返回统一错误码 return new ResultVO<>(ResultCode.VALIDATE_FAILED, defaultMessage); } @ExceptionHandler(APIException.class) public ResultVO<String> apiExceptionHandler(APIException exception) { return new ResultVO<>(ResultCode.FAILED, exception.getMsg()); } } <file_sep>package com.hhit.demo.mapper; import com.hhit.demo.domain.User; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; /** * @author wangxiaopeng */ @Mapper public interface UserMapper { /** * @param id 用户id * @return 返回用户对象 */ User getUser(Long id); } <file_sep>package com.hhit.demo.service.Impl; import com.hhit.demo.domain.User; import com.hhit.demo.mapper.UserMapper; import com.hhit.demo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @author wangxiaopeng */ @Service public class UserServiceImpl implements UserService { @Autowired UserMapper userMapper; @Override public String addUser(User user) { return "success"; } @Override public User getUser(Long id) { return userMapper.getUser(id); } } <file_sep>package com.hhit.demo.domain; import com.hhit.demo.annotation.ExceptionCode; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * @author wangxiaopeng */ @Data public class User { @ApiModelProperty("用户账号") @NotNull(message = "用户账号不能为空") @Size(min=6, max=11, message = "账号长度必须是6-16个字符") @ExceptionCode(value = 100001, message = "账号验证错误") private String account; @ApiModelProperty("用户密码") @NotNull(message = "用户密码不能为空") @Size(min=6, max=11, message = "密码长度必须是6-16个字符") @ExceptionCode(value = 100002, message = "密码验证错误") private String password; @ApiModelProperty("用户邮箱") @NotNull(message = "用户邮箱不能为空") @Email(message = "邮箱格式不对") @ExceptionCode(value = 100003, message = "邮箱验证错误") private String email; }
e42fbd4ba510a683f5203a5f765f95c7c9762e34
[ "Java" ]
5
Java
chris118/java-demo
8b0054bc65962dccad8eb523787fb75d17ef0a18
740913577f7ba6c92cbcfc1db68f0cc7abb8c24c
refs/heads/master
<file_sep># django-wordcounter ## 개요 1. 소개 2. 사진 3. 기능 4. 한계 및 과제 * * * ## 소개 멋쟁이사자처럼 django 입문 강의에서 사용된 첫번째 프로젝트이다. 기초 레벨 수준의 프로젝트로, View에서 파이썬으로 가공한 데이터를 Template으로 데이터를 옮기는 과정을 연습하기 위해 만든 프로젝트이다. 긴 본문을 입력하면, 총 단어의 수가 몇 개 있는지, 그리고 각 단어는 본문 내에서 몇 번 등장하는지를 알려준다 꾸미는 과정은 Bootstrap으로 꾸몄다. * * * ## 사진 ![wordcounter1](/wordcounter1.png "wordcounter1") ![wordcounter2](/wordcounter2.png "wordcounter2") ![wordcounter3](/wordcounter3.png "wordcounter3") ![wordcounter4](/wordcounter4.png "wordcounter4") * * * ## 기능 1. 총 단어 세기 2. 각 단어 수 세기 3. fontawsome에서 끌어온 아이콘에 github, sns 저장소 링크 남기기 4. about 페이지 5. 공백 포함, 미포함별 총 단어 수 세기 선택 버튼 (과제) * * * ## 한계 및 과제 #### 1. 한계 : 본문 입력을 GET방식으로 하는건 사실 옳지 못하다. POST방식으로 보내줘야 하는데, 아직 수업때 다루지 않았으므로 (나중에 다룰 예정이므로) 아직은 GET방식으로 하기로 한다. #### 2. 과제 : 공백포함-미포함별 단어 세기를 구현해보기. 우리가 구현한 것은 공백을 포함하지 않은 총 단어 수이다. 공백을 포함한 총 단어수는 간단히 "공백제외 단어 수 + 공백 수"라고 볼 수 있는데, 공백 수는 단순히 "공백제외 단어 수 -1 개"이다. 따라서 공백 포함 총 단어 수는 (공백제외 단어 수 X 2 - 1) 개 이다. <file_sep>from django.contrib import admin from django.urls import path import wordcount.views urlpatterns = [ path('admin/', admin.site.urls), path('', wordcount.views.home, name="home"), path('about/', wordcount.views.about, name="about"), path('result/', wordcount.views.result, name="result"), path('English/', wordcount.views.English, name="English"), path('Korea/', wordcount.views.Korea, name="Korea"), ]
68d77eb7f13db0aabe1755c24e8b03c58490904e
[ "Markdown", "Python" ]
2
Markdown
BAEKINSEONG/classlion-.2
a520147e5d4e7bbcd5009fe9347e36d1a1818118
a9bb5a6b899c1230881fcccdde1b9479de5a1023
refs/heads/master
<repo_name>SimenB/storybook-start-bug<file_sep>/components/story.js import * as React from 'react'; import { storiesOf } from '@storybook/react'; storiesOf('Test', module).add('example', () => <hr />);
2add5592abf72348f651f5069c6a63c96394a9bd
[ "JavaScript" ]
1
JavaScript
SimenB/storybook-start-bug
fb72ced0d43feb1713fffa11bd20856752307dc5
6ad904c9404216f92339babf4918c43378b455f0
refs/heads/master
<repo_name>burryleak/ChemTools.Classes<file_sep>/Element.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BurryLeak.ChemTools { public struct Element { public string Name { get; } public string Symbol { get; } public float fMass { get; } public int dwAtomicNumber { get; } /// <summary> /// Создает структуру под хранения элемента /// </summary> /// <param name="sSymbol">Строка с символом</param> /// <param name="sName">Строка с названием</param> /// <param name="fMass">Атомная масса элемента</param> /// <param name="dwAtomicNumber">Атомный номер элемента</param> public Element(string sSymbol, string sName, float fMass, int dwAtomicNumber) { this.Name = sName; this.Symbol = sSymbol; this.fMass = fMass; this.dwAtomicNumber = dwAtomicNumber; } } } <file_sep>/Formula.cs using System; using System.Collections.Generic; namespace BurryLeak.ChemTools { /// <summary> /// Класс, представляющий химическую формулу как набор FormulaItem /// </summary> public class Formula { /// <summary> /// Класс, реализующий структурную единицу формулы - атом или радикал /// </summary> public class FormulaItem : ICloneable { /// <summary> /// Содержание структурной единицы /// </summary> public string Content { get; set; } /// <summary> /// Индекс структурной единицы (число атомов/группировок) /// </summary> public float fIndex { get; set; } /// <summary> /// Индекс родительского элемента, необходим для парсинга скобок /// </summary> private float fParentIndex { get; set; } /// <summary> /// Создает структурный элемент /// </summary> /// <param name="Content">Содержание структурной единицы</param> /// <param name="fIndex">Индекс</param> /// <param name="fParentIndex">Индекс родительского элемента</param> public FormulaItem(string Content, float fIndex, float fParentIndex) { this.Content = Content; this.fIndex = fParentIndex * fIndex; this.fParentIndex = fParentIndex; } public FormulaItem(string Content, float fIndex) { this.Content = Content; this.fIndex = fIndex; fParentIndex = 0; } public object Clone() { FormulaItem newNode = new FormulaItem(Content, fIndex); return newNode; } private FormulaItem() { } } //Переменные для внутреннего использования и соответствующие поля string FormulaString; List<FormulaItem> Nodes; public List<FormulaItem> FormulaItems { get { return Nodes; } } private Formula() { } /// <summary> /// Создает экземпляр формулы и автоматически запускает парсинг входной строки /// </summary> /// <param name="FormulaString">Сама химическая формула</param> public Formula(string FormulaString) { this.FormulaString = FormulaString; //Если есть пробелы - их необходимо удалить while (this.FormulaString.Contains(" ")) this.FormulaString = this.FormulaString.Remove(this.FormulaString.IndexOf(' '),1); Nodes = Parse(this.FormulaString, 1); OptimizeNodes(); } public override string ToString() { return FormulaString; } /// <summary> /// Внутренняя функция, объединяющая повторяющиеся структурные единицы, должны выполнится после завершения общей функции Parse(). /// </summary> private void OptimizeNodes() { //Создаем новый список, где будем хранить уже объединенные элементы List<FormulaItem> NewNodes = new List<FormulaItem>(); //Обходим каждый элемент существующего списка структурных единиц foreach (var node in Nodes) { //Смотрим, существует ли такой сорт единиц в новом списке //Если да, то этот элемент пропускается, поскольку позже мы разом добавляем элементы из ВСЕГО старого списка bool IsInNewNodes = false; foreach (var n in NewNodes) if (n.Content == node.Content) { IsInNewNodes = true; break; } if (IsInNewNodes) continue; //Если такого элемента в новом списке нет, необходимо его создать FormulaItem newNode = new FormulaItem(node.Content, 0); //Суммируем все такие же индексы для этого элемнета по всему старому списку for(int i = 0; i < Nodes.Count; i++) { if (node.Content == Nodes[i].Content) newNode.fIndex += Nodes[i].fIndex; } //Добавляем... NewNodes.Add(newNode); } //Заменяем старый список новым Nodes = NewNodes; } /// <summary> /// Внутренняя функция для метода Parse(), добавляющая новый элемент в список структурных единиц, исходя из временных строк. Очищает временные строки после добавления. /// </summary> /// <param name="TempNodes">Ссылка на список, в который добавляем элемент</param> /// <param name="sTempContent">Ссылка на строку содержимого (очищается после отработки метода!)</param> /// <param name="sTempIndex">Ссылка на строку с индексом (очищается после отработки метода!)</param> /// <param name="fParentIndex">Индекс родительского элемента</param> private void AddTempValues(ref List<FormulaItem> TempNodes, ref string sTempContent, ref string sTempIndex, float fParentIndex) { float fTempIndex = 0; //Если индекса и не было - он равен 1 if (sTempIndex == "") fTempIndex = 1.0f; else { //Необходимо заменить все точки на запятые, дабы не было исключения sTempIndex = sTempIndex.Replace('.', ','); fTempIndex = Single.Parse(sTempIndex); } //Добавляем новый элемент FormulaItem newNode = new FormulaItem(sTempContent, fTempIndex, fParentIndex); TempNodes.Add(newNode); //Очищаем временые строки sTempContent = ""; sTempIndex = ""; } /// <summary> /// Основной метод парсинга строки. Разбивает на структурные единицы (атомы/радикалы/группировки) и возвращает построенный список структурных единиц. /// </summary> /// <param name="sInput">Строка, которую необходимо разбить на структурные единицы</param> /// <param name="fParentIndex">Индекс родительского элемента, на который умножатся все индексы внутри строки</param> /// <returns>Список структурных единиц в данной строке</returns> private List<FormulaItem> Parse(string sInput, float fParentIndex) { //Инициализируем новый список ст. единиц List<FormulaItem> nodes = new List<FormulaItem>(); //Нулевой символ в конце нужен для правильной обработки случая конца строки //Да, костыль, простите, как умеем... sInput += '\0'; //Временные строки для хранения прочитанного посимвольно содержимого и индекса ст. единицы string sTempContent = ""; string sTempIndex = ""; //Пробегаемся по каждому элементу for (int i = 0; i < sInput.Length; i++) { char cSymbol = sInput[i]; //Заглавная буква - значит либо начало, либо до этого что-то было, и это что-то надо добавить if (cSymbol >= 'A' && cSymbol <= 'Z') { if (sTempContent != "") AddTempValues(ref nodes, ref sTempContent, ref sTempIndex, fParentIndex); sTempContent += cSymbol; } //Строчные буквы просто добавляем, кстати это позволяет обозначать орг. радикалы маленькими буквами, но в скобках... //...случайно вышло... if (cSymbol >= 'a' && cSymbol <= 'z') sTempContent += cSymbol; //Если это символ, который может содержаться в записи индекса, добавляем его к индексам if ((cSymbol >= '0' && cSymbol <= '9') || cSymbol == '.' || cSymbol == ',') sTempIndex += cSymbol; //Главные танцы : если это открывающаяся скобка - if (cSymbol == '[' || cSymbol == '(') { //Если до этого во временных переменных что-то было - самое время это добавить if (sTempContent != "") AddTempValues(ref nodes, ref sTempContent, ref sTempIndex, fParentIndex); //Определяем, на какую закрывающуюся скобку ориентируемся char cPair = cSymbol == '[' ? ']' : ')'; //Здесь храним позицию последнего символа, односящегося к этой скобке, включая индекс int dwEndPos = 0; //Метка, которая должна равнятся 0, когда скобка сбалансирована int dwStatus = 1; //Временные строки, для хранения содержимого скобки string sInternalContent = ""; string sInternalIndex = ""; //Структурные элементы, содержащиеся в этой скобке List<FormulaItem> InternalNodes = new List<FormulaItem>(); bool IsPairFound = false; for (int j = i + 1; j < sInput.Length; j++) { //Если парная скобка не найдена, можем менять статус if (!IsPairFound) { if (sInput[j] == cSymbol) dwStatus++; else if (sInput[j] == cPair) dwStatus--; } if (dwStatus == 0) { //Как только скобка найдена - заполняем флаг if (!IsPairFound) IsPairFound = true; //Извлекаем подстроку содержимого скобки if (sInternalContent == "") sInternalContent = sInput.Substring(i + 1, j - i - 1); //читаем индекс else { if ((sInput[j] >= '0' && sInput[j] <= '9') || sInput[j] == '.' || sInput[j] == ',') sInternalIndex += sInput[j]; else { //Если индекс закончился, запоминаем, куда необходимо будет передвинуть указатель по выходу dwEndPos = j; float fInternalIndex = 1.0f; if (sInternalIndex != "") fInternalIndex = Single.Parse(sInternalIndex.Replace('.', ',')); //Парсим содержимое скобки InternalNodes = Parse(sInternalContent, fInternalIndex*fParentIndex); //Объединяем списки nodes.AddRange(InternalNodes); //Передвигаем указатель на последний символ индекса (если он есть) и выходим из цикла по чтению скобки i = dwEndPos - 1; break; } } } } //Генерируем сообщение, если где-то были несбалансированные скобки if (dwStatus != 0) throw new FormatException("Non-balanced brackets!"); } //еще обработка звездочек if (cSymbol == '*') { //Строки для коэффициента перед веществом и самого вещества string sTempCoeff = ""; string sInternalContent = ""; //Чмиаем до конца for (int j = i + 1; j < sInput.Length; j++) { //Если это цифра и контента при этом нет - это коэффициент, читаем его if (sInput[j] >= '0' && sInput[j] <= '9' && sInternalContent == "") sTempCoeff += sInput[j]; //...иначе это уже контент else if (sInput[j] != '*' && j != sInput.Length - 1) sInternalContent += sInput[j]; else { //Если это или звездочка или конец строки, можно записать float fCoeff = 1.0f; if (sTempCoeff != "") { sTempCoeff = sTempCoeff.Replace('.', ','); fCoeff = Single.Parse(sTempCoeff); } List<FormulaItem> InternalNodes = Parse(sInternalContent, fParentIndex * fCoeff); nodes.AddRange(InternalNodes); //Передвигаем указатель и выходим из цикла i = j - 1; break; } } } } //Добавляем последнее, если оно есть if (sTempContent != "") AddTempValues(ref nodes, ref sTempContent, ref sTempIndex, fParentIndex); //Удаляем тот самый костыльный ноль и уходим в закат sInput.Remove(sInput.Length - 1); return nodes; } } } <file_sep>/README.md # ChemTools.Classes На сегодняшний день, это: 1. Класс Formula, описывающий химическое соединение; пока что способно только создаваться по входной строке с формулой. 2. Класс FormulaItem, описывающий структурную единицу формулы. 3. Класс Element, описывающий известный химический элемент. 4. Класс Manager, который управляет загрузкой/выгрузкой данных. <file_sep>/ConsoleMethods.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BurryLeak.ChemTools { partial class Debugspace { /// <summary> /// Показывает сообщение об ошибке и, если надо, выходит из приложения. /// </summary> /// <param name="ErrorMessage">Сообщение об ошибке</param> /// <param name="IsExit">Необходимо ли выходить из приложения</param> static void PrintError(string ErrorMessage, bool IsExit) { ConsoleColor c = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("ERROR :: {0}", ErrorMessage); Console.ForegroundColor = c; if (IsExit) { Console.WriteLine("Press any key to exit..."); Console.ReadKey(true); Environment.Exit(0); } } /// <summary> /// Выводит на консоль текст определенного цвета. /// </summary> /// <param name="Text">Выводимый текст</param> /// <param name="TextColor">Цвет текста</param> /// <param name="IsLine">Добавлять ли перенос на новую строку</param> static void PrintText(string Text, ConsoleColor TextColor, bool IsLine) { ConsoleColor c = Console.ForegroundColor; Console.ForegroundColor = TextColor; Console.Write(Text); if (IsLine) Console.Write("\n"); Console.ForegroundColor = c; } } } <file_sep>/ChemToolsManager.cs using System; using System.Collections.Generic; using System.IO; namespace BurryLeak.ChemTools { public static class ChemToolsManager { /// <summary> /// Загружает список химических элементов из файла. /// В каждой строке файла по одному элементу, части строки разделены <b>символом табуляции</b>. /// Формат : ат.номер-символ-название-масса (где "-" - символ табуляции) /// /// </summary> /// <param name="sPathToList">Путь до файла с элементами</param> /// <exception cref="FileNotFoundException"></exception> /// <exception cref="FormatException"></exception> /// <returns>Список элементов</returns> public static List<Element> LoadElements(string sPathToList) { List<Element> list = new List<Element>(); using (FileStream fs = File.Open(sPathToList, FileMode.Open)) { StreamReader sr = new StreamReader(fs); int lineIndex = 1; while (!sr.EndOfStream) { string line = sr.ReadLine(); string[] parts = line.Split('\t'); if (parts.Length != 4) throw new FormatException(String.Format("Invalid line format! Line #{0}", lineIndex)); parts[3] = parts[3].Replace('.', ','); Element e = new Element(parts[1], parts[2], Single.Parse(parts[3]), Int32.Parse(parts[0])); list.Add(e); lineIndex++; } } if (list.Count == 0) throw new Exception("Empty list!"); return list; } } }
78ceb4052fdc0264295c7675e6d1f9dbaf400c32
[ "Markdown", "C#" ]
5
C#
burryleak/ChemTools.Classes
417e76865e2d2e6bf56a0434b1db6f46727b41dd
88aeef89477f7e1a7742a9c4fa298ea6927457a3
refs/heads/master
<file_sep>#!/usr/bin/env bash if [ `uname -s` == 'Darwin' ]; then CROSSTOOL_BUILD_PLATFORM=osx-`uname -m` elif [ `uname -s` == 'Linux' ]; then CROSSTOOL_BUILD_PLATFORM=linux-`uname -m` else echo "Error: '`uname -s`' is not a supported platform" exit 1 fi if [ ! -d configs/${CROSSTOOL_BUILD_PLATFORM} ]; then echo "Error: There are no scripts available for '${CROSSTOOL_BUILD_PLATFORM}'. The build platforms are:" for i in configs/* ; do echo \* $(basename $i) ; done exit 1 fi if [ -z "$1" -o ! -d "configs/${CROSSTOOL_BUILD_PLATFORM}/$1" ]; then echo "Error: You must specify a host platform. The host platforms for '${CROSSTOOL_BUILD_PLATFORM}' are" for i in configs/${CROSSTOOL_BUILD_PLATFORM}/* ; do echo \* $(basename $i) ; done exit 1 fi export CROSSTOOL_ROOT_FOLDER=`pwd` export CROSSTOOL_TOOLCHAIN_NAME=${CROSSTOOL_BUILD_PLATFORM}/$1 ulimit -n 1024 (cd configs/${CROSSTOOL_TOOLCHAIN_NAME} && ct-ng menuconfig) <file_sep>Please do not remove me - I exist so this directory can exist on git to cache downloaded sources.
695828da64f9ad95bf15b15b15fefacd71996355
[ "Markdown", "Shell" ]
2
Shell
isabella232/crosstool-configs
d6380dd6fcec0a90e864ee491d3127465791622d
9079fd6dc21c5b9b5bccc0be2194c95a57062056
refs/heads/master
<file_sep>using Exam.Model; using System.Web.Mvc; namespace Exam.Web.Controllers { public class CustomerController : Controller { private readonly CustomerRepository _repository; public CustomerController() { _repository = new CustomerRepository(); } public ActionResult Index() { return View(_repository.GetList()); } public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(Customer customer) { if (!ModelState.IsValid) return View(customer); _repository.Add(customer); return RedirectToAction("Index"); } public ActionResult Edit(int id) { var customer = _repository.GetById(id); if (customer == null) return RedirectToAction("Index"); return View(customer); } [HttpPost] public ActionResult Edit(Customer customer) { if (!ModelState.IsValid) return View(customer); _repository.Update(customer); return RedirectToAction("Index"); } public ActionResult Delete(int id) { var customer = _repository.GetById(id); if (customer == null) return RedirectToAction("Index"); return View(customer); } [HttpPost] public ActionResult Delete(Customer customer) { _repository.Delete(customer); return RedirectToAction("Index"); } public ActionResult Details(int id) { var customer = _repository.GetById(id); if (customer == null) return RedirectToAction("Index"); return View(customer); } } }<file_sep>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; namespace Exam.Repository { public class BaseRepository<T> : IRepository<T> where T:class { private readonly SalesDbContext _context; public BaseRepository() { _context = new SalesDbContext(); } public int Add(T entity) { _context.Entry(entity).State = EntityState.Added; return _context.SaveChanges(); } public int Delete(T entity) { _context.Entry(entity).State = EntityState.Deleted; return _context.SaveChanges(); } public T GetById(Expression<Func<T, bool>> match) { return _context.Set<T>().FirstOrDefault(match); } public IEnumerable<T> GetList() { return _context.Set<T>(); } public int Update(T entityOld, T entity) { var attachedEntry = _context.Entry(entityOld); attachedEntry.CurrentValues.SetValues(entity); return _context.SaveChanges(); } } } <file_sep>using Exam.Model; using System.Data.Entity; using System.Data.Entity.ModelConfiguration.Conventions; namespace Exam.Repository { public class SalesDbContext:DbContext { public SalesDbContext() :base("NetFundamentals") { Database.SetInitializer<SalesDbContext>(null); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Customer>().ToTable("Customers"); modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); } public DbSet<Customer> Customer { get; set; } } } <file_sep>using Exam.Model; using Exam.Repository; using System.Linq; using System.Web.Http; namespace Exam.Api.Controllers { public class CustomerController : ApiController { private readonly BaseRepository<Customer> _repository; public CustomerController() { _repository = new BaseRepository<Customer>(); } [HttpPut] public IHttpActionResult Create(Customer customer) { if (!ModelState.IsValid) return BadRequest(ModelState); return Ok(_repository.Add(customer)); } [HttpPost] public IHttpActionResult Update(Customer customer) { var oldCustomer = _repository.GetById(x => x.CustomerId == customer.CustomerId); if (oldCustomer == null) return NotFound(); return Ok(_repository.Update(oldCustomer, customer)); } [HttpGet] public IHttpActionResult Get(int id) { return Ok(_repository.GetById(x => x.CustomerId == id)); } [HttpGet] public IHttpActionResult Get() { var list = _repository.GetList().Take(30).ToList(); return Ok(list); } [HttpDelete] public IHttpActionResult Delete(Customer customer) { return Ok(_repository.Delete(customer)); } } } <file_sep>using Exam.Model; using RestSharp; using System.Collections.Generic; namespace Exam.Web { public class CustomerRepository { public const string URL_API = "http://localhost:58536/api"; public List<Customer> GetList() { var client = new RestClient(URL_API); var request = new RestRequest(Method.GET); request.Resource = "/customer"; return client.Execute<List<Customer>>(request).Data; } public void Add(Customer customer) { var client = new RestClient(URL_API); var request = new RestRequest(Method.PUT); request.Resource = "/customer"; request.AddJsonBody(customer); client.Execute(request); } public Customer GetById(int id) { var client = new RestClient(URL_API); var request = new RestRequest(Method.GET); request.Resource = $"/customer/{id}"; return client.Execute<Customer>(request).Data; } public void Update(Customer customer) { var client = new RestClient(URL_API); var request = new RestRequest(Method.POST); request.Resource = "/customer"; request.AddJsonBody(customer); client.Execute(request); } public void Delete(Customer customer) { var client = new RestClient(URL_API); var request = new RestRequest(Method.DELETE); request.Resource = "/customer"; request.AddJsonBody(customer); client.Execute(request); } } }
5b96614eb0981bcaf3fe5b9cad8c2a5d95826f6f
[ "C#" ]
5
C#
johngt81/ExamMvc
ef4355d501ff7bc54e14cf7fbba08f2df5f89621
3dec562e54bb690c43ad4317363ed59b68d4f5c1
refs/heads/master
<file_sep>#include "ObjectArchive.hpp" #include "GameObject.hpp" #include "Transform.hpp" using namespace FishEngine; #if 0 void FishEngine::ObjectOutputArchive::SerializeObject_impl(FishEngine::ObjectPtr const & obj) { if (obj == nullptr) { (*this) << nullptr; return; } auto instanceID = obj->GetInstanceID(); auto classID = obj->ClassID(); auto find_result = m_serialized.find(instanceID); bool serialized = false; int fileID = -1; if (find_result != m_serialized.end()) // has already serialized { fileID = find_result->second; serialized = true; } else { fileID = m_nextFileID; m_totalCount++; m_nextFileID = m_totalCount + 1; //m_serialized[instanceID] = fileID; } if (m_isInsideDoc) { BeginFlow(); BeginMap(1); // do not know map size if (classID == ClassID<Mesh>()) { auto importer = AssetImporter::GetAtPath(AssetDatabase::GetAssetPath(obj)); (*this) << FishEngine::make_nvp("fileID", importer->m_recycleNameToFileID[obj->name()]); (*this) << FishEngine::make_nvp("guid", importer->GetGUID()); } //else if (classID == ClassID<Material>()) //{ // (*this) << FishEngine::make_nvp("fileID", instanceID); //} //else if (classID == ClassID<Shader>()) //{ // (*this) << FishEngine::make_nvp("fileID", instanceID); //} else { (*this) << FishEngine::make_nvp("fileID", fileID); } EndMap(); } if (serialized) { return; } bool isComponent = FishEngine::IsComponent(classID); bool isGameobject = FishEngine::IsGameObject(classID); bool isPrefab = obj->ClassID() == FishEngine::ClassID<FishEngine::Prefab>(); if (!(isComponent || isGameobject || isPrefab)) { return; } if (m_isInsideDoc) { m_objectsToBeSerialized.push_back({ fileID, obj }); } else { m_serialized[instanceID] = fileID; //AssetOutputArchive::SerializeObject(obj); BeginDoc(classID, fileID); BeginMap(2); m_emitter << obj->ClassName(); BeginMap(1); // do not know map size obj->Serialize(*this); EndMap(); EndMap(); EndDoc(); } } void FishEngine::ObjectOutputArchive::SerializeObject(FishEngine::ObjectPtr const & object) { int classID = object->ClassID(); bool isComponent = FishEngine::IsComponent(classID); bool isTransform = object->ClassID() == ClassID<Transform>(); bool isGameobject = FishEngine::IsGameObject(classID); //bool isPrefab = object->ClassID() == FishEngine::ClassID<FishEngine::Prefab>(); if (isGameobject) { //auto go = GameObject::Create(); //auto go = object->Clone(); } if (isTransform) { // auto transform = object->Clone(); } SerializeObject_impl(object); while (!m_objectsToBeSerialized.empty() && !m_isInsideDoc) { auto item = m_objectsToBeSerialized.front(); m_objectsToBeSerialized.pop_front(); int fileID = item.first; auto obj = item.second; m_nextFileID = fileID; SerializeObject_impl(obj); } } #endif<file_sep>#pragma once #include "../../Archive.hpp" #include "../NameValuePair.hpp" namespace FishEngine { class BinaryOutputArchive; template <> constexpr int ArchiveID<BinaryOutputArchive>() { return 2; } class BinaryOutputArchive : public OutputArchive { public: BinaryOutputArchive(std::ostream & ostream) : m_ostream(ostream) {} BinaryOutputArchive(BinaryOutputArchive const &) = delete; BinaryOutputArchive& operator = (BinaryOutputArchive const &) = delete; ~BinaryOutputArchive() = default; virtual int ArchiveID() { return FishEngine::ArchiveID<BinaryOutputArchive>(); } void SaveBinary(const void * data, std::size_t size) { auto const writtenSize = static_cast<std::size_t>(m_ostream.rdbuf()->sputn(reinterpret_cast<const char*>(data), size)); if (writtenSize != size) { //throw Exception("Failed to write " + std::to_string(size) + " bytes to output stream! Wrote " + std::to_string(writtenSize)); abort(); } } template<typename T, std::enable_if_t<std::is_enum<T>::value, int> = 0> BinaryOutputArchive & operator << (T t) { SaveBinary(std::addressof(t), sizeof(t)); return *this; } BinaryOutputArchive & operator << (std::string const & str) { SaveBinary(str.data(), str.size()); return *this; } template<class T> BinaryOutputArchive & operator << (NameValuePair<T> const & t) { (*this) << t.value; return *this; } //! Serialization for std::vectors of arithmetic (but not bool) using binary serialization template<typename T, typename std::enable_if_t<std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, int> = 0> BinaryOutputArchive & operator << (const std::vector<T> & v) { (*this) << v.size(); SaveBinary(v.data(), v.size() * sizeof(T)); return *this; } //! Serialization for non-arithmetic vector types template<typename T, typename std::enable_if_t<!std::is_arithmetic<T>::value, int> = 0> BinaryOutputArchive & operator << (const std::vector<T> & v) { (*this) << v.size(); for (auto && x : v) { (*this) << x; } return *this; } template<class T, class B> BinaryOutputArchive & operator << (std::map<T, B> const & v) { //(*this) << make_size_tag(v.size()); (*this) << v.size(); for (auto& p : v) { (*this) << p.first << p.second; } } //template<typename T, typename std::enable_if_t<std::is_base_of<Object, T>::value, int> = 0> BinaryOutputArchive & operator << (ObjectPtr const & object); private: std::ostream & m_ostream; }; } <file_sep>#pragma once #include <iostream> #include "../../ReflectClass.hpp" namespace FishEngine { class Meta(NonSerializable) BinaryOutputArchive { public: BinaryOutputArchive(std::ostream & stream) : m_stream(stream) { } BinaryOutputArchive& operator = (BinaryOutputArchive const &) = delete; ~BinaryOutputArchive() noexcept = default; void SaveBinary(const void * data, std::size_t size) { auto const written_size = static_cast<std::size_t>(m_stream.rdbuf()->sputn(reinterpret_cast<const char*>(data), size)); if (written_size != size) { abort(); } } private: std::ostream & m_stream; }; class Meta(NonSerializable) BinaryInputArchive { public: BinaryInputArchive(std::istream & stream) : m_stream(stream) { } BinaryInputArchive & operator = (BinaryInputArchive const &) = delete; ~BinaryInputArchive() noexcept = default; void LoadBinary(void * const data, std::size_t size) { auto const read_size = static_cast<std::size_t>(m_stream.rdbuf()->sgetn(reinterpret_cast<char*>(data), size)); if (read_size != size) { abort(); } } private: std::istream & m_stream; }; template<typename T, std::enable_if_t<std::is_arithmetic<T>::value || std::is_enum<T>::value, int> = 0> BinaryOutputArchive & operator << (BinaryOutputArchive & archive, T const & t) { archive.SaveBinary(std::addressof(t), sizeof(t)); return archive; } template<typename T, std::enable_if_t<std::is_arithmetic<T>::value || std::is_enum<T>::value, int> = 0> BinaryInputArchive & operator >> (BinaryInputArchive & archive, T & t) { archive.LoadBinary(std::addressof(t), sizeof(t)); return archive; } /************************************************************************/ /* std::string */ /************************************************************************/ static BinaryOutputArchive & operator << (BinaryOutputArchive & archive, const std::string & str) { archive << str.size(); archive.SaveBinary(str.data(), str.size()); return archive; } static BinaryInputArchive & operator >> (BinaryInputArchive & archive, std::string & str) { std::size_t size = 0; archive >> size; str.resize(size); archive.LoadBinary(const_cast<char *>(str.data()), size); return archive; } /************************************************************************/ /* UUID */ /************************************************************************/ static BinaryOutputArchive & operator << (BinaryOutputArchive& archive, FishEngine::UUID const & t) { //static_assert(sizeof(t) == 16, "Error"); archive.SaveBinary(t.data, sizeof(t)); return archive; } static BinaryInputArchive & operator >> (BinaryInputArchive& archive, FishEngine::UUID & t) { //static_assert(sizeof(t) == 16, "Error"); archive.LoadBinary(t.data, sizeof(t)); return archive; } template<class T> static BinaryOutputArchive & operator << (BinaryOutputArchive & archive, T * v) = delete; template<class T> static BinaryInputArchive & operator >> (BinaryInputArchive & archive, T * t) = delete; } <file_sep>#include "AssetDataBase.hpp" #include <Debug.hpp> #include <Texture.hpp> #include <AssetImporter.hpp> #include <Application.hpp> using namespace FishEngine; namespace FishEditor { std::map<FishEngine::Path, QIcon> AssetDatabase::s_cacheIcons; std::set<std::shared_ptr<FishEngine::Object>> AssetDatabase::s_allAssetObjects; FishEngine::GUID AssetDatabase::AssetPathToGUID(FishEngine::Path const & path) { return AssetImporter::s_pathToImpoter[path]->GetGUID(); } //Path AssetDatabase::GUIDToAssetPath(const boost::uuids::uuid &guid) // { // return AssetImporter::s_objectInstanceIDToPath[guid]; // } FishEngine::Path AssetDatabase::GetAssetPath(int instanceID) { return AssetImporter::s_objectInstanceIDToPath[instanceID]; } FishEngine::Path AssetDatabase::GetAssetPath(FishEngine::ObjectPtr assetObject) { return GetAssetPath(assetObject->GetInstanceID()); } const QIcon & AssetDatabase::GetCacheIcon(FishEngine::Path path) { static QIcon unknown_icon(":/Resources/unknown_file.png"); static QIcon material_icon(":/Resources/MaterialIcon.png"); static QIcon mesh_icon(":/Resources/MeshIcon.png"); static QIcon prefab_icon(":/Resources/PrefabIcon.png"); static QIcon shader_icon(":/Resources/project_icon_shader.png"); static QIcon audioclip_icon(":/Resources/project_icon_audioclip.png"); auto type = FishEngine::Resources::GetAssetType(path.extension()); if (type == FishEngine::AssetType::Material) { return material_icon; } else if (type == FishEngine::AssetType::Shader) { return shader_icon; } else if (type == FishEngine::AssetType::Prefab) { return prefab_icon; } else if (type == FishEngine::AssetType::Model) { return mesh_icon; } else if (type == FishEngine::AssetType::AudioClip) { return audioclip_icon; } else if (type == FishEngine::AssetType::Texture) { auto it = s_cacheIcons.find(path); if (it != s_cacheIcons.end()) { return it->second; } // s_cacheIcons.emplace(path, QIcon(QString::fromStdString(path.string()))); // return s_cacheIcons[path]; } return unknown_icon; } FishEngine::ObjectPtr AssetDatabase::LoadAssetAtPath(FishEngine::Path const & path) { FishEngine::Path p; if (path.is_absolute()) { LogWarning("AssetDatabase::LoadAssetAtPath, path should be relative to project root dir, eg. Assets/a.fbx"); p = path; } else { p = FishEngine::Application::dataPath().parent_path() / path; } if (!boost::filesystem::exists(p)) { return nullptr; } auto importer = AssetImporter::GetAtPath(p); if (importer == nullptr) return nullptr; //return As<T>( AssetImporter::s_importerGUIDToObject[importer->GetGUID()] ); return importer->asset()->mainObject(); } } <file_sep>#pragma once #include <iostream> #include "../../ReflectClass.hpp" #include "../../GUID.hpp" namespace FishEngine { class Meta(NonSerializable) TextOutputArchive { public: TextOutputArchive(std::ostream & stream) : m_stream(stream) { } TextOutputArchive& operator = (TextOutputArchive const &) = delete; ~TextOutputArchive() noexcept = default; template<typename T> void Save ( T const & t) { m_stream << t << std::endl; } // template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, int> = 0> // TextOutputArchive & operator << (T const & t) // { // this->Save(t); // return *this; // } private: std::ostream & m_stream; }; class Meta(NonSerializable) TextInputArchive { public: TextInputArchive(std::istream & stream) : m_stream(stream) { } TextInputArchive& operator = (TextInputArchive const &) = delete; ~TextInputArchive() noexcept = default; template<typename T> void Load ( T & t ) { m_stream >> t; } private: std::istream & m_stream; }; /************************************************************************/ /* arithmetic */ /************************************************************************/ template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, int> = 0> TextOutputArchive & operator << ( TextOutputArchive & archive, T const & t) { archive.Save(t); return archive; } template<typename T, std::enable_if_t<std::is_arithmetic<T>::value, int> = 0> TextInputArchive & operator >> ( TextInputArchive & archive, T & t ) { archive.Load(t); return archive; } /************************************************************************/ /* enums */ /************************************************************************/ template<typename T, std::enable_if_t<std::is_enum<T>::value, int> = 0> TextOutputArchive & operator << ( TextOutputArchive & archive, T const & t ) { //archive.Save(std::string(FishEngine::EnumToString(t))); archive.Save(static_cast<uint32_t>(t)); return archive; } template<typename T, std::enable_if_t<std::is_enum<T>::value, int> = 0> TextInputArchive & operator >> ( TextInputArchive & archive, T & t ) { //archive.Load(std::string(FishEngine::EnumToString(t))); uint32_t e; archive.Load(e); t = static_cast<T>(e); return archive; } /************************************************************************/ /* std::string */ /************************************************************************/ TextOutputArchive & operator << (TextOutputArchive & archive, std::string const & t) { archive.Save(t); return archive; } TextInputArchive & operator >> (TextInputArchive & archive, std::string & t) { archive.Load(t); return archive; } /************************************************************************/ /* UUID */ /************************************************************************/ static TextOutputArchive & operator << (TextOutputArchive & archive, GUID const & t) { archive << ToString(t); return archive; } } <file_sep>#include "BinaryOutputArchive.hpp" #include "../../Object.hpp" namespace FishEngine { BinaryOutputArchive & FishEngine::BinaryOutputArchive::operator<<(ObjectPtr const & object) { object->Serialize(*this); return *this; } } <file_sep>CMAKE_MINIMUM_REQUIRED(VERSION 3.0.0 FATAL_ERROR) PROJECT(FishEngine CXX) SET(FISHENGINE_VERSION_MAJOR 0) SET(FISHENGINE_VERSION_MINOR 1) SET(FISHENGINE_VERSION_PATCH 0) SET(FISHENGINE_VERSION ${FISHENGINE_VERSION_MAJOR}.${FISHENGINE_VERSION_MINOR}.${FISHENGINE_VERSION_PATCH}) # Global compile & linker flags # Target at least C++14 set(CMAKE_CXX_STANDARD 14) SET_PROPERTY(GLOBAL PROPERTY USE_FOLDERS ON) # Output set(CMAKE_BINARY_DIR ${CMAKE_CURRENT_LIST_DIR}/Binary) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) #set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) set(FISHENGINE_SCRIPT_DIR ${CMAKE_CURRENT_LIST_DIR}/../Script) #message("lib output directory: " ${CMAKE_BINARY_DIR}/lib/${CMAKE_BUILD_TYPE}) #SET(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} ${CMAKE_CURRENT_LIST_DIR}/ThirdParty/boost_1_63/) #SET(CMAKE_LIBRARY_PATH ${CMAKE_LIBRARY_PATH} ${CMAKE_CURRENT_LIST_DIR}/ThirdParty/boost_1_63/lib64-msvc-14.0) #boost set(Boost_USE_STATIC_LIBS ON) set(Boost_USE_MULTITHREADED ON) set(Boost_USE_STATIC_RUNTIME OFF) find_package(Boost 1.59 REQUIRED COMPONENTS system filesystem) include_directories(${Boost_INCLUDE_DIRS}) MESSAGE("Found Boost: " ${Boost_INCLUDE_DIRS}) # # Autodesk FBX sdk # SET( FBXSDK_DIR "" CACHE PATH "Autodesk FBX SDK root directory" ) # include_directories( ${FBXSDK_DIR}/include ) # IF (WIN32) # SET( FBXSDK_LIB_DIR ${FBXSDK_DIR}/lib/vs2015/x64 ) # SET( FBXSDK_LIB_DEBUG ${FBXSDK_LIB_DIR}/debug/libfbxsdk-md.lib ) # SET( FBXSDK_LIB_RELEASE ${FBXSDK_LIB_DIR}/release/libfbxsdk-md.lib ) # ELSE() # SET( FBXSDK_LIB_DIR ${FBXSDK_DIR}/lib/clang ) # SET( FBXSDK_LIB_DEBUG ${FBXSDK_LIB_DIR}/debug/libfbxsdk.a ) # SET( FBXSDK_LIB_RELEASE ${FBXSDK_LIB_DIR}/release/libfbxsdk.a ) # ENDIF() # IF(NOT EXISTS ${FBXSDK_LIB_DEBUG}) # MESSAGE(FATAL_ERROR "${FBXSDK_LIB_DEBUG} not found") # ENDIF () # IF(NOT EXISTS ${FBXSDK_LIB_RELEASE}) # MESSAGE(FATAL_ERROR "${FBXSDK_LIB_RELEASE} not found") # ENDIF () # SET( FBXSDK_LIB debug ${FBXSDK_LIB_DEBUG} optimized ${FBXSDK_LIB_RELEASE} ) # fmod SET( FMOD_DIR ${CMAKE_CURRENT_LIST_DIR}/ThirdParty/fmod) include_directories( ${FMOD_DIR}/include ) IF (WIN32) SET( FMOD_LIB_DEBUG ${FMOD_DIR}/lib/fmodL64_vc.lib) SET( FMOD_LIB_RELEASE ${FMOD_DIR}/lib/fmod64_vc.lib) ELSE() SET( FMOD_LIB_DEBUG ${FMOD_DIR}/lib/libfmodL.dylib) SET( FMOD_LIB_RELEASE ${FMOD_DIR}/lib/libfmod.dylib) ENDIF() SET( FMOD_LIB debug ${FMOD_LIB_DEBUG} optimized ${FMOD_LIB_RELEASE} ) # python27 # SET( PYTHON27_DIR ${CMAKE_CURRENT_LIST_DIR}/ThirdParty/python27 ) # include_directories( ${PYTHON27_DIR}/include ) # IF (WIN32) # SET( PYTHON27_LIB debug ${PYTHON27_DIR}/libs/python27.lib optimized ${PYTHON27_DIR}/libs/python27.lib ) # ELSE() # SET( PYTHON27_LIB ${PYTHON27_DIR}/lib/libpython27.a ) # ENDIF() # IF (WIN32) # SET( PYTHON3_DIR ${CMAKE_CURRENT_LIST_DIR}/ThirdParty/python3 ) # include_directories( ${PYTHON3_DIR}/include ) # SET( PYTHON3_LIB debug ${PYTHON3_DIR}/libs/python35.lib optimized ${PYTHON3_DIR}/libs/python35.lib ) # ELSE() # SET( PYTHON3_DIR ${CMAKE_CURRENT_LIST_DIR}/ThirdParty/python3 ) # #include_directories( ${PYTHON3_DIR}/include ) # include_directories( /Users/yushroom/.pyenv/versions/3.6.1/include/python3.6m ) # #SET( PYTHON3_LIB debug ${PYTHON3_DIR}/libs/libpython3.6dm.a optimized ${PYTHON3_DIR}/libs/libpython3.6m.a ) # SET( PYTHON3_LIB /Users/yushroom/.pyenv/versions/3.6.1/lib/libpython3.6m.a ) # ENDIF() include_directories(./Source/Runtime) include_directories(./ThirdParty/) #include_directories(./ThirdParty/PVR/Framework) #include_directories(./ThirdParty/PhysXSDK/Include/) #include_directories(./ThirdParty/assimp/include) # glfw set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE) set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE) set(GLFW_INSTALL OFF CACHE BOOL "" FORCE) ADD_SUBDIRECTORY(./ThirdParty/glfw/) include_directories(./ThirdParty/glfw/include) SET_TARGET_PROPERTIES(glfw PROPERTIES FOLDER "ThirdParty") if (MSVC) set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4251" ) add_definitions(-D_CRT_SECURE_NO_WARNINGS=1) include_directories(./ThirdParty/glew/include) #set(BUILD_UTILS OFF CACHE BOOL "" FORCE) ADD_SUBDIRECTORY(./ThirdParty/glew/build/cmake) # set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MTd") # set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT") # set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /MTd") # set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} /MT") SET_TARGET_PROPERTIES(glew PROPERTIES FOLDER "ThirdParty/glew") SET_TARGET_PROPERTIES(glew_s PROPERTIES FOLDER "ThirdParty/glew") else() #ADD_SUBDIRECTORY(./ThirdParty/glfw/) #SET_TARGET_PROPERTIES(glfw PROPERTIES FOLDER "ThirdParty") #include_directories(./ThirdParty/glfw/include) # link_directories(${CMAKE_CURRENT_LIST_DIR}/ThirdParty/libs/osx/) endif() include_directories(./ThirdParty/yaml-cpp/include) set(YAML_CPP_BUILD_TOOLS OFF CACHE BOOL "" FORCE) #set(BUILD_SHARED_LIBS ON CACHE BOOL "" FORCE) ADD_SUBDIRECTORY(./ThirdParty/yaml-cpp) SET_TARGET_PROPERTIES(yaml-cpp PROPERTIES FOLDER "ThirdParty/yaml-cpp") SET_TARGET_PROPERTIES(format PROPERTIES FOLDER "ThirdParty/yaml-cpp") #set(GLEW_LIBRARIES ${CMAKE_CURRENT_LIST_DIR}/ThirdParty/glew-2.0.0/lib/Release/Win32/glew32.lib) #IF(NOT EXISTS ${GLEW_LIBRARIES}) # message(FATAL_ERROR "GLEW lib does not exist: ${GLEW_LIBRARIES}") #endif () # set(ASSIMP_NO_EXPORT ON CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_ASSIMP_TOOLS OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_SAMPLES OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_TESTS OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_3DS_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_3D_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_3MF_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_AC_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_ASE_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_ASSBIN_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_ASSXML_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_B3D_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_BLEND_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_BVH_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_COB_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_COLLADA_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_CSM_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_DXF_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_GLTF_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_HMP_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_IFC_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_IRRMESH_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_IRR_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_LWO_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_LWS_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_MD2_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_MD3_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_MD5_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_MDC_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_MDL_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_MS3D_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_NDO_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_NFF_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_OFF_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_OGRE_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_OPENGEX_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_PLY_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_Q3BSP_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_Q3D_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_RAW_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_SIB_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_SMD_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_STL_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_TERRAGEN_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_XGL_IMPORTER OFF CACHE BOOL "" FORCE) # set(ASSIMP_BUILD_X_IMPORTER OFF CACHE BOOL "" FORCE) # set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) # if (MSVC) # set(ASSIMP_BUILD_ZLIB ON CACHE BOOL "" FORCE) # endif() # set( CMAKE_BUILD_TYPE_COPY "${CMAKE_BUILD_TYPE}") # set( CMAKE_BUILD_TYPE "Release") # ADD_SUBDIRECTORY(./ThirdParty/assimp) # SET_TARGET_PROPERTIES(assimp PROPERTIES FOLDER "ThirdParty") # set( CMAKE_BUILD_TYPE ${CMAKE_BUILD_TYPE_COPY} ) SET( PhysX_ROOT_DIR "" CACHE PATH "PhysXSDK root directory" ) include_directories( ${PhysX_ROOT_DIR}/Include ) include_directories( ${PhysX_ROOT_DIR}/../ ) if (MSVC) #SET_TARGET_PROPERTIES(zlibstatic PROPERTIES FOLDER "ThirdParty") #SET_TARGET_PROPERTIES(UpdateAssimpLibsDebugSymbolsAndDLLs PROPERTIES FOLDER "ThirdParty") #target_link_libraries(FishEditor opengl32.lib) # PhysXSDK # set(PhysX_ROOT_DIR ${CMAKE_CURRENT_LIST_DIR}/ThirdParty/PhysXSDK) set(PhysXSDK_LIBRARIES_DIR ${PhysX_ROOT_DIR}/Lib/vc14win64) set(PhysXSDK_LIBRARIES "") foreach(x PhysX3 PhysX3Common PhysX3Cooking) set(lib1 ${PhysXSDK_LIBRARIES_DIR}/${x}DEBUG_x64.lib) set(lib2 ${PhysXSDK_LIBRARIES_DIR}/${x}CHECKED_x64.lib) IF(NOT EXISTS ${lib1}) message(FATAL_ERROR "physx root directory does not exist: ${lib1}") endif () IF(NOT EXISTS ${lib2}) message(FATAL_ERROR "physx root directory does not exist: ${lib2}") endif () list (APPEND PhysXSDK_LIBRARIES debug ${lib1} optimized ${lib2}) endforeach() foreach(x PhysX3Extensions PhysX3Vehicle PhysXProfileSDK PhysXVisualDebuggerSDK PxTask) set(lib1 ${PhysXSDK_LIBRARIES_DIR}/${x}DEBUG.lib) set(lib2 ${PhysXSDK_LIBRARIES_DIR}/${x}CHECKED.lib) IF(NOT EXISTS ${lib1}) message(FATAL_ERROR "physx root directory does not exist: ${lib1}") endif () IF(NOT EXISTS ${lib2}) message(FATAL_ERROR "physx root directory does not exist: ${lib2}") endif () list (APPEND PhysXSDK_LIBRARIES debug ${lib1} optimized ${lib2}) endforeach() else() FILE(GLOB PhysXSDK_LIBRARIES ${PhysX_ROOT_DIR}/Lib/osx64/*.a) endif() add_definitions(-DFishEngine_SHARED_LIB=1) ADD_SUBDIRECTORY(./Source/Runtime) ADD_SUBDIRECTORY(./Source/Game) ADD_SUBDIRECTORY(./Source/Editor) ADD_SUBDIRECTORY(./Source/Tool) ADD_SUBDIRECTORY(./Source/Test)<file_sep>#include <Serialization/archives/YAMLArchive.hpp> #include <cassert> namespace FishEngine { class ObjectInputArchive : public InputArchive { }; class ObjectOutputArchive : public YAMLOutputArchive { public: ObjectOutputArchive(std::ostream & os) : YAMLOutputArchive(os) { } virtual ~ObjectOutputArchive() = default; virtual void BeginDoc() override { // call BeginDoc(int classID, int fileID) instead abort(); } void BeginDoc(int classID, int fileID) { assert(!m_isInsideDoc); m_isInsideDoc = true; m_emitter.EmitBeginDoc_FishEngine(classID, fileID); } virtual void EndDoc() override { m_isInsideDoc = false; m_emitter.EmitEndDoc_FishEngine(); } protected: virtual void SerializeObject(FishEngine::ObjectPtr const & object) override; int m_nextFileID = 1; int m_totalCount = 0; private: void SerializeObject_impl(FishEngine::ObjectPtr const & obj); std::map<int, int> m_serialized; // instanceID to fileID std::deque<std::pair<int, std::shared_ptr<FishEngine::Object>>> m_objectsToBeSerialized; // fileID bool m_isInsideDoc = false; }; }<file_sep>#ifndef Debug_hpp #define Debug_hpp #include "FishEngine.hpp" #include "ReflectClass.hpp" #include "StringFormat.hpp" namespace FishEngine { enum class LogChannel { Info, Warning, Error }; class FE_EXPORT Meta(NonSerializable) Debug { public: Debug() = delete; // Logs message to the Console. //static void Log(const char *format, ...); //static void _Log(const std::string & message); // A variant of Debug.Log that logs a warning message to the console. //static void LogWarning(const char *format, ...); //static void _LogWarning(const std::string & message); // A variant of Debug.Log that logs an error message to the console. //static void LogError(const char *format, ...); //static void _LogError(const std::string & message); static void Log(LogChannel channel, std::string const & message, const char* file, int line, const char * func); static void setColorMode(bool value) { s_colorMode = value; } static void Init(); private: static bool s_colorMode; }; } #if defined(_MSC_VER) #define __PRETTY_FUNCTION__ __FUNCTION__ #endif #define LogInfo(message) FishEngine::Debug::Log(FishEngine::LogChannel::Info, (message), __FILE__, __LINE__, __PRETTY_FUNCTION__) #define LogWarning(message) FishEngine::Debug::Log(FishEngine::LogChannel::Warning, (message), __FILE__, __LINE__, __PRETTY_FUNCTION__) #define LogError(message) FishEngine::Debug::Log(FishEngine::LogChannel::Error, (message), __FILE__, __LINE__, __PRETTY_FUNCTION__) #endif /* Debug_hpp */ <file_sep>#ifndef App_hpp #define App_hpp #include <ReflectClass.hpp> namespace FishEditor { class Meta(NonSerializable) App { public: virtual ~App() = 0; virtual void Init() = 0; //virtual void Update() = 0; //virtual void Clean() = 0; }; } #endif // App_hpp
27bc2e895e134f24c6cb97a3f4e5309902c7fbed
[ "CMake", "C++" ]
10
C++
Husain136/FishEngine
7d3e8e02a4f5514edb089da2a81f67495b89a1d8
e9178b720b33d426e9438d92fa8f68d1151d6bf5
refs/heads/master
<file_sep># About this project This project could be your basis for the development of a kotlin bot. ### About Traze More information about [Traze](https://github.com/iteratec/traze) # Your challenge Will you beat the current running bot or your friends as a client on the [javascript gui](https://iteratec.github.io/traze-javascript-vanilla/)? ### Getting started Some seconds after running the project, you can see your movement [here](https://traze.iteratec.de/watch/) by your "bike" moving north. ### Your tasks You have to implement a bot logic. Therefore, you need to process the received grid and players data by the given four todos in the code. <file_sep>import org.json.JSONObject class TrazeBot( var botSecretUserToken: String?, var botPlayerId: Int? ) { fun initBot(playerJsonString: String) { val bot = JSONObject(playerJsonString) this.botPlayerId = bot.get("id") as Int this.botSecretUserToken = bot.get("secretUserToken").toString() println("Bot " + bot.get("name") + " erfolgreich registriert!") } } <file_sep>import org.eclipse.paho.client.mqttv3.* import org.json.JSONObject import java.util.* fun main(args: Array<String>) { println ("Start der Anwendung") val mqttClientId = UUID.randomUUID().toString() val botName = "kotlin-bot-" + Math.round((Math.random() * 50) + 1) val brokerUri = "tcp://traze.iteratec.de:1883" val mqttClient = MqttClient(brokerUri, mqttClientId) val myBroker = BrokerClient(mqttClientId, botName, mqttClient) val myGame = Game(null, null) val myTraceBot = TrazeBot(null, null) val myGrid = Grid() myBroker.initGame(myBroker, myGame, myTraceBot, myGrid) } fun botLogic(myBroker: BrokerClient, myGame: Game, myTraceBot: TrazeBot) { Thread.sleep(3_000) //Optimization? better wait until objects are set up // todo implement your bot logic // exmaple for publish a message - steering sendSteering("N", myBroker, myGame, myTraceBot) } fun sendSteering(direction: String, myBroker: BrokerClient, myGame: Game, myTraceBot: TrazeBot) { // Input {"course":"N", "playerToken": "<PASSWORD>"} val sterringBikeJson = JSONObject("{\"course\": \"" + direction + "\", \"playerToken\": \"" + myTraceBot.botSecretUserToken + "\"}") val msg = MqttMessage() msg.payload = sterringBikeJson.toString().toByteArray() // println("publish steering: ${sterringBikeJson.toString()}") myBroker.mqttClient.publish("traze/${myGame.instanceName}/${myTraceBot.botPlayerId}/steer", msg) println("Richtung versendet \"Ende\"") }<file_sep>class Game( var instanceName: String?, var activePlayers: String? ) { fun updateGameInstance( gameString: String ) { //InputForm: [{"activePlayers":1,"name":"1"}] this.activePlayers = gameString.split(":", ",")[1] this.instanceName = gameString.split(":", ",")[3].removeSurrounding("\"").replace("}", "").replace("]", "") .replace("\"", "") } fun updatePlayers(playersString: String) { println(playersString) try { // todo evaluate the players data } catch (e: Exception) { e.printStackTrace() } } fun updateTicker(tickerString: String) { println(tickerString) try { // todo may evaluate the ticker data } catch (e: Exception) { e.printStackTrace() } } } <file_sep>import org.json.JSONObject class Grid() { fun updateGrid(gridInformation: String) { val gridJson = JSONObject(gridInformation) println(gridJson) // todo evaluate the grid data } } <file_sep>rootProject.name = 'traze-bot-kotlin' <file_sep>import org.eclipse.paho.client.mqttv3.MqttClient import org.eclipse.paho.client.mqttv3.MqttConnectOptions import org.eclipse.paho.client.mqttv3.MqttMessage import org.json.JSONObject class BrokerClient( var mqttClientId: String, val botName: String, var mqttClient: MqttClient ) { fun initGame(myBroker: BrokerClient, myGame: Game, myTraceBot: TrazeBot, myGrid: Grid) { try { //Connection to the Server connectToServer() //Callback for the Informationsaving in Objects val theCallback = SimpleMqttCallBack(myBroker, myGame, myTraceBot, myGrid) this.mqttClient.setCallback(theCallback) //Subscribe the game mqttClient.subscribe("traze/games") myBroker.joinOnGrid(myGame) mqttClient.subscribe("traze/${myGame.instanceName}/grid") mqttClient.subscribe("traze/${myGame.instanceName}/players") mqttClient.subscribe("traze/${myGame.instanceName}/ticker") mqttClient.subscribe("traze/${myGame.instanceName}/player/${this.mqttClientId}") //SubscribeAndJoin-> Subscribe for all topics and Join the Game afterwards //BrokerClient.Subscribe is called from Game.updateGameInstance, after the instanceName is known botLogic(myBroker, myGame, myTraceBot) } catch (e: Exception) { e.printStackTrace() } } private fun connectToServer() { try { val options = MqttConnectOptions() options.isCleanSession = true mqttClient.connect(options) if (mqttClient.isConnected) { println("Client und Server sind verbunden") } else { println("KEINE Verbindung") } } catch (e: Exception) { e.printStackTrace() } } private fun joinOnGrid(myGame: Game) { try { // Input {"name": "myIngameNick", "mqttClientName": "myClientName"} val joiningPlayer = JSONObject("{\"name\": \"" + this.botName + "\", \"mqttClientName\": \"" + this.mqttClientId + "\"}") val message = MqttMessage() message.payload = joiningPlayer.toString().toByteArray() // println("publish join: ${joiningPlayer.toString()}") mqttClient.publish("traze/${myGame.instanceName}/join", message) } catch (e: Exception) { e.printStackTrace() } } } <file_sep>import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken import org.eclipse.paho.client.mqttv3.MqttCallback import org.eclipse.paho.client.mqttv3.MqttMessage class SimpleMqttCallBack( var myBroker: BrokerClient, var myGame: Game, var myTraceBot: TrazeBot, var myGrid: Grid ) : MqttCallback { override fun connectionLost(throwable: Throwable) { println("Connection to MQTT broker lost!") System.exit(0) } @Throws(Exception::class) override fun messageArrived(topic: String, newMqttMessage: MqttMessage) { when (topic) { "traze/games" -> myGame.updateGameInstance(String(newMqttMessage.payload)) "traze/${myGame.instanceName}/grid" -> myGrid.updateGrid(String(newMqttMessage.payload)) "traze/${myGame.instanceName}/player/${myBroker.mqttClientId}" -> myTraceBot.initBot(String(newMqttMessage.payload)) "traze/${myGame.instanceName}/players" -> myGame.updatePlayers(String(newMqttMessage.payload)) "traze/${myGame.instanceName}/ticker" -> myGame.updateTicker(String(newMqttMessage.payload)) } } override fun deliveryComplete(iMqttDeliveryToken: IMqttDeliveryToken) { // not used } }
fb0931ba120f1e5bb2f075f13832ec14fe5382b1
[ "Markdown", "Kotlin", "Gradle" ]
8
Markdown
iteratec/traze-bot-kotlin
9d7a240f73ba8938e74946c493685f44226b2d36
fafd64614cbb3e656bda272bc124fdf29add1367
refs/heads/master
<file_sep>var React = require('react'); var ItemList = require('./components/item-list.js'); var Application = React.createClass({ /*componentWillMount: function() { console.log('Application.componentWillMount'); }, componentDidMount: function() { console.log('Application.componentDidMount'); }, componentWillReceiveProps: function() { console.log('Application.componentWillReceiveProps'); }, shouldComponentUpdate: function() { console.log('Application.shouldComponentUpdate'); }, componentWillUpdate: function() { console.log('Application.componentWillUpdate'); }, componentDidUpdate: function() { console.log('Application.componentDidUpdate'); }, componentWillUnmount: function() { console.log('Application.componentWillUnmount'); },*/ /*getDefaultProps: function() { console.log('Application.getDefaultProps'); }, getInitialState: function() { console.log('Application.getInitialState'); return null; },*/ render: function() { console.log('Application.render'); return <div className="container"><ItemList /></div>; } }); React.render(<Application />, document.getElementsByClassName('main-container')[0]);<file_sep>var React = require('react'); var gsapReactPlugin = require('gsap-react-plugin'); var MyButton = React.createClass({ componentDidMount: function() { console.log('MyButton.componentDidMount'); TweenLite.to(this, 1, {state: {width: 100}, onUpdate: this.onUpdate}); //console.log(this.state); }, onUpdate: function(){ //console.log('onUpdate'); //this.setState({width: this.state.width}); }, /*componentWillMount: function() { console.log('MyButton.componentWillMount'); }, componentDidMount: function() { console.log('MyButton.componentDidMount'); }, componentWillReceiveProps: function() { console.log('MyButton.componentWillReceiveProps'); }, shouldComponentUpdate: function() { console.log('MyButton.shouldComponentUpdate'); }, componentWillUpdate: function() { console.log('MyButton.componentWillUpdate'); }, componentDidUpdate: function() { console.log('MyButton.componentDidUpdate'); }, componentWillUnmount: function() { console.log('MyButton.componentWillUnmount'); }, getDefaultProps: function() { console.log('MyButton.getDefaultProps'); }, onMouseDown: function() { console.log('MyButton.onMouseDown'); }, onMouseUp: function() { console.log('MyButton.onMouseUp'); }, onMouseEnter: function() { console.log('MyButton.onMouseEnter'); }, onMouseLeave: function() { console.log('MyButton.onMouseLeave'); },*/ getDefaultProps: function() { console.log('MyButton.getDefaultProps'); }, getInitialState: function() { console.log('MyButton.getInitialState'); return {width: 0}; }, render: function() { console.log('MyButton.render'); return <button className="clickable-button" onMouseDown={this.onMouseDown} onMouseUp={this.onMouseUp} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave} style={{width:this.state.width}} > Add an item </button>; } }); module.exports = MyButton;<file_sep>var React = require('react'); var PlusButton = require('./button.js'); var Item = React.createClass({ /*componentWillMount: function() { console.log('Item.componentWillMount'); }, componentDidMount: function() { console.log('Item.componentDidMount'); }, componentWillReceiveProps: function() { console.log('Item.componentWillReceiveProps'); }, shouldComponentUpdate: function() { console.log('Item.shouldComponentUpdate'); }, componentWillUpdate: function() { console.log('Item.componentWillUpdate'); }, componentDidUpdate: function() { console.log('Item.componentDidUpdate'); }, componentWillUnmount: function() { console.log('Item.componentWillUnmount'); }, onMouseDown: function() { console.log('Item.onMouseDown'); }, onMouseUp: function() { console.log('Item.onMouseUp'); }, onMouseEnter: function() { console.log('Item.onMouseEnter'); }, onMouseLeave: function() { console.log('Item.onMouseLeave'); },*/ /*getDefaultProps: function() { console.log('Item.getDefaultProps'); }, getInitialState: function() { console.log('Item.getInitialState'); return null; },*/ render: function() { console.log('Item.render'); return <div className="todo-item" onMouseDown={this.onMouseDown} onMouseUp={this.onMouseUp} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave} ><PlusButton /></div>; } }); module.exports = Item;<file_sep>var gulp = require('gulp'); var browserSync = require('browser-sync'); var reload = require('browser-sync').reload; var concat = require('gulp-concat'); var watchify = require('watchify'); var reactify = require('reactify'); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); var assign = require('lodash.assign'); var browserify = require('browserify'); var gutil = require('gulp-util'); gulp.task('dev:html', function() { return gulp.src('./app/src/*.html').pipe(gulp.dest('./app/dist')).pipe(reload({stream: true})); }); gulp.task('dev:css', function() { return gulp.src('./app/src/css/*.css').pipe(concat('app.css')).pipe(gulp.dest('./app/dist/css')).pipe(reload({stream: true})); }); gulp.task('dev:js', function() { var customOpts = { entries: ['./app/src/js/main.js'], debug: true }; var opts = assign({}, watchify.args, customOpts); var b = watchify(browserify(opts)); b.transform([reactify]); b.on('update', bundle); b.on('log', gutil.log); function bundle() { return b.bundle() .on('error', function(err) { delete err.stream; console.log(err); }) .pipe(source('app.js')) .pipe(buffer()) .pipe(gulp.dest('./app/dist/js')) .pipe(browserSync.stream()); } bundle(); }); gulp.task('browserSync', function() { browserSync({ open: false, port: 3031, minify: false, server: { baseDir: './app/dist' } }); gulp.watch(['./app/src/css/*.css'], ['dev:css']); gulp.watch(['./app/src/*.html'], ['dev:html']); }); gulp.task('default', ['browserSync','dev:js','dev:html','dev:css']);<file_sep># react-tryout-0.2 react-tryout-0.2
cbea0b00de35b114e4b0df9c3e5f29e0017eafe8
[ "JavaScript", "Markdown" ]
5
JavaScript
TahirAhmed/react-tryout-0.2
0e921170d931baf69ef21d9eaad2ebed9ce79b0f
e13a865d08732151e815440701ba2a01b0cd40c1
refs/heads/master
<file_sep>import './index.scss'; console.warn('member/index.js');<file_sep>import './app.scss'; import('./home/index.js'); import('./goods/index.js'); console.warn('app.js');<file_sep>'use strict'; const assert = require('assert'); const path = require('path'); const fs = require('fs'); const _ = require('lodash'); const writeJson = require('write-json'); const getTargetFile = (files = [], suffix = '.js') => { let file = undefined; for (let i = 0; i < files.length; i++) { const temp = files[i]; if (temp.endsWith(suffix)) { if (!file) { file = temp; } else { // 构建过程中,会存在其他插件生成额外的 js 文件,影响输出 // 例如 热更新中的 hot-update:app.171443217f5176a47fb9.hot-update.js temp.length < file.length ? temp : file; } } } return file; } /** * 初始转换 entry 入口 */ const initConvertEntry = function() { console.warn(this.entry); console.warn('into initConvertEntry ===<'); if ((typeof this.entry == 'string') || (this.entry instanceof Array)) { console.warn('entry need convert'); this.entry = { main: this.entry, } } } class EntrypointsOutputWebpackPlugin { constructor(options = {}) { this.options = options; } apply(compiler) { const options = this.options || {}; compiler.hooks.emit.tapAsync( 'entrypoints-output-webpack-plugin', (compilation, callback) => { const entrypoints = compilation.entrypoints || new Map(); const entrypointsKeys = entrypoints.keys(); const entrypointsIterator = entrypoints.entries(); const showFullPath = options.showFullPath || false; const initOutput = options.initOutput || {}; const outputData = Object.assign({}, initOutput); const publicPath = compiler.options.output.publicPath; const output = options.output || compiler.options.output.path; const filename = options.filename || '.entrypoints.json'; const filepath = path.resolve(output, filename); if (/\.+\.json$/.test(filename)) { assert(null, 'options.filename Must be json file, for example: ".entrypoints.json"'); } for (let [key, value] of entrypointsIterator) { // rendered 表示已经构建执行完毕? // 是否需要判断 rendered ? // value.chunks[0].rendered const files = _.get(value, 'chunks[0].files', []); const js = getTargetFile(files, '.js'); const css = getTargetFile(files, '.css'); outputData[key] = {}; if (js) { outputData[key].js = showFullPath ? `${publicPath}${js}` : js; } if (css) { outputData[key].css = showFullPath ? `${publicPath}${css}` : css; } }; writeJson(filepath, outputData); callback(); } ); // Compile 开始进入编译环境,开始编译 // Compilation 即将产生第一个版本 // make任务开始 // optimize作为Compilation的回调方法,优化编译,在Compilation回调函数中可以为每一个新的编译绑定回调。 // after-compile编译完成 // emit准备生成文件,开始释放生成的资源,最后一次添加资源到资源集合的机会 // after-emit文件生成之后,编译器释放资源 } } module.exports = EntrypointsOutputWebpackPlugin;<file_sep>## entrypoints-output-webpack-plugin webpack 插件,构建输出 output 文件配置,包含 js 与 css 输出资源,webpack >= 4.0.0 ### 使用示例 ```javascript const EntrypointsOutputWebpackPlugin = require('entrypoints-output-webpack-plugin'); new EntrypointsOutputWebpackPlugin({ // // 是否展示全部路径,设置为 ture 时会加上 webpack 配置中的 output.publicPath // showFullPath: true, // // 输出目录,必须写绝对路径,不传入时,默认使用 webpack 配置中的 output.path // output: path.join(__dirname, '../a/b/c'), // // 输出 json 文件名,默认为 “.entrypoints.json” // filename: 'a.json', // // filename: '.entrypoints.json', // // 初始输出,输出的文件夹中除了默认的 entrypoints ,还会包含 initOutput 中的值 // initOutput: { // init: { // js: 'https://www.google.com/xxx.js', // css: 'https://a.b.com/x/y/z.css', // }, // }, }), ``` ### option 参数说明 参数 | 类型 | 是否必传 | 默认值 | 说明 -------- | --- | --- | --- | --- showFullPath | Boolean | 否 | false | 是否展示全部路径,设置为 ture 时会加上 webpack 配置中的 output.publicPath output | String | 否 | 默认使用 webpack 配置中的 output.path | 输出目录,必须写绝对路径,不传入时,默认使用 webpack 配置中的 output.path filename | String | 否 | .entrypoints.json | 输出 json 文件名,默认为 “.entrypoints.json” initOutput | Object | 否 | null | 初始输出,输出的文件夹中除了默认的 entrypoints ,还会包含 initOutput 中的值<file_sep>import './index.scss'; console.warn('order/index.js');
4da6710dc4ebf73832ee08b20bff9d900b64dbce
[ "JavaScript", "Markdown" ]
5
JavaScript
pyrinelaw/entrypoints-output-webpack-plugin
10ad3f3be0c21d0365fce9710d03c7e7e7f04927
2a92ac3e31d44f81a4b1acc69eb62fef80787665
refs/heads/master
<file_sep>```python from django.db import models from django.conf import settings # Create your models here. class User(models.Model): username = models.TextField() class Article(models.Model): title = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) class Comment(models.Model): content = models.TextField() article = models.ForeignKey(Article, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) ``` ```python u1 = User.objects.create(username='Kim') u2 = User.objects.create(username='Lee') a1 = Article.objects.create(title='1글', user=u1) a2 = Article.objects.create(title='2글', user=u2) a3 = Article.objects.create(title='3글', user=u2) a4 = Article.objects.create(title='4글', user=u2) c1 = Comment.objects.create(content='1글1댓', article=a1, user=u2) c2 = Comment.objects.create(content='1글2댓', article=a1, user=u2) c3 = Comment.objects.create(content='2글1댓', article=a2, user=u1) c4 = Comment.objects.create(content='4글1댓', article=a4, user=u1) c5 = Comment.objects.create(content='3글1댓', article=a3, user=u2) c6 = Comment.objects.create(content='3글2댓', article=a3, user=u1) ``` 1. 모든 댓글 출력 ```python comments = Comment.objects.all() for comment in comments: print(comment.content) ``` 2. 1번 사람(u1) 작성한 모든 게시글 ```python u1.article_set.all() Article.objects.filter(user=u1) Article.objects.filter(user_id=1) ``` 3. 2번 댓글(c2)을 작성한 사람 ```python c2.user.username ``` 4. 3번째 글을 작성한 사람의 이름 ```python a3.user.username ``` 5. 2번 글(a2)을 작성한 사람이 작성한 댓글들 ```python a2.user.comment_set.all() ``` 6. 1번 글(a1)에 작성된 댓글 중에 첫번째를 작성한 사람의 이름 ```python a1.comment_set.all()[0].user.username ``` 7. 1번 사람(u1)이 작성한 첫번째 게시글의 1,2번째 댓글 ```python u1.article_set.all()[0].comment_set.all()[0:2] ``` 8. 2번 사람(u2)이 작성한 게시글을 제목 내림차순으로 정렬 ```python u2.article_set.order_by('-title') ``` <file_sep>from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings # Create your models here. class User(AbstractUser): # 확장 가능성을 위해 직접 만들어서 사용 권장 followers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followings', blank=True)<file_sep>from django.shortcuts import render, redirect, get_object_or_404 from IPython import embed from django.views.decorators.http import require_POST from django.contrib.auth.decorators import login_required from django.contrib import messages from django.core.exceptions import PermissionDenied # from accounts.models import User from django.http import HttpResponseForbidden, JsonResponse, HttpResponse from django.contrib.auth import get_user_model from IPython import embed from .forms import ArticleForm, CommentForm from .models import Article, Comment, HashTag # Create your views here. def index(request): articles = Article.objects.order_by('-id') context = { 'articles': articles } # embed() return render(request, 'articles/index.html', context) # def new(request): # if request.method == 'GET': # return render(request, 'articles/new.html') @login_required def create(request): # if not request.user.is_authenticated: # messages.error(request, '로그인해') # return redirect('articles:index') if request.method == 'POST': # POST 요청 -> 검증 및 저장 로직 # title = request.POST.get('title') # content = request.POST.get('content') article_form = ArticleForm(request.POST, request.FILES) if article_form.is_valid(): # 검증에 성공하면 저장 # title = article_form.cleaned_data.get('title') # content = article_form.cleaned_data.get('content') # article = Article(title=title, content=content) article = article_form.save(commit=False) article.user = request.user # User class의 객체 article.save() # 해시태그 저장 및 연결 작업 for word in article.content.split(): if word.startswith('#'): hashtag, created = HashTag.objects.get_or_create(content=word) article.hashtags.add(hashtag) # if HashTag.objects.filter(content=word).exists(): # hashtag = HashTag.objects.get(content=word) # try: # hashtag = HashTag.objects.get(content=word) # except: # article = article_form.save(commit=False) # article.image = request.FILES.get('image') # embed() # article.save() return redirect('articles:detail', article.pk) # else: # return form -> 중복되서 제거 else: # GET 요청 -> Form article_form = ArticleForm() # GET -> 비어있는 Form context # POST -> 검증 실패시 에러메세지와 입력값 다시 context context = { 'article_form': article_form } return render(request, 'articles/form.html', context) def detail(request, article_pk): # article = Article.objects.get(pk=article_pk) article = get_object_or_404(Article, pk=article_pk) comments = article.comment_set.all() comment_form = CommentForm() a = ['22', '33', '44'] context = { 'article': article, 'comments': comments, 'comment_form': comment_form, 'a': a } return render(request, 'articles/detail.html', context) @require_POST def delete(request, article_pk): article = Article.objects.get(pk=article_pk) if article.user == request.user: # if request.method == 'POST': article.delete() return redirect('articles:index') else: raise PermissionDenied # else: # return redirect('articles:detail', article_pk) # def edit(request, article_pk): # if request.method == 'GET': # article = Article.objects.get(pk=article_pk) # context = { # 'article': article # } # return render(request, 'articles/edit.html', context) # else: # article = Article.objects.get(pk=article_pk) # article.title = request.POST.get('title') # article.content = request.POST.get('content') # article.save() # return redirect('articles:detail', article.pk) def update(request, article_pk): article = get_object_or_404(Article, pk=article_pk) if request.user == article.user: # if request.user != article.user: # return redirect('articles:detail', article_pk) if request.method == 'POST': article_form = ArticleForm(request.POST, instance=article) # 수정할 대상이 article이기 때문에 instance로 입력 설정 if article_form.is_valid(): # article.title = article_form.cleaned_data.get('title') # article.content = article_form.cleaned_data.get('content') # article.save() article = article_form.save() # 해시태그 수정 article.hashtags.clear() for word in article.content.split(): if word.startswith('#'): hashtag, created = HashTag.objects.get_or_create(content=word) article.hashtags.add(hashtag) return redirect('articles:detail', article.pk) else: # article_form = ArticleForm( # initial={ # 'title': article.title, # 'content': article.content # } # ) article_form = ArticleForm(instance=article) context = { 'article': article, 'article_form':article_form } return render(request, 'articles/form.html', context) else: return HttpResponseForbidden() @require_POST def comment_create(request, article_pk): if request.user.is_authenticated: article = get_object_or_404(Article, pk=article_pk) # 1. modelform에 사용자 입력값 넣고 comment_form = CommentForm(request.POST) # ModelForm instance # 2. 검증 if comment_form.is_valid(): # 3. 맞으면 저장 # 3-1. 사용자 입력값으로 comment instance 생성 (저장은 X) comment = comment_form.save(commit=False) # comment object로 리턴된다. # 3-2. Foreign key를 입력하고 저장 comment.article = article comment.user = request.user comment.save() # DB에 쿼리 # 4. return redirect else: messages.success(request, '댓글이 형식이 맞지 않습니다.') return redirect('articles:detail', article_pk) else: return HttpResponse('Unauthorized', status=401) # article = Article.objects.get(pk=article_pk) # comment = Comment() # comment.content = request.POST.get('comment_content') # comment.article = article # comment.article_id = article_pk # comment.save() # return redirect('articles:detail', article.pk) @require_POST @login_required def comment_delete(request, article_pk, comment_pk): comment = Comment.objects.get(pk=comment_pk) if request.user == comment.user: comment.delete() # messages.add_message(request, messages.INFO, '댓글이 삭제 되었습니다.') messages.success(request, '댓글이 삭제되었습니다.') return redirect('articles:detail', article_pk) else: return HttpResponseForbidden() @login_required def like(request, article_pk): # 좋아요를 눌렀다면 if request.is_ajax(): article = Article.objects.get(pk=article_pk) if request.user in article.like_users.all(): # 좋아요 취소 로직 article.like_users.remove(request.user) is_liked = False # 아니면 else: # 좋아요 로직 article.like_users.add(request.user) is_liked = True context = { 'is_liked': is_liked, 'like_count': article.like_users.count() } return JsonResponse(context) else: return HttpResponseForbidden() def hashtag(request, tag_pk): hashtag = get_object_or_404(HashTag, pk=tag_pk) context = { 'hashtag': hashtag } return render(request, 'articles/hashtag.html', context) def explore(request): from itertools import chain # 내 친구들이(request.user.followings) 작성한 것 + 내가(request.user) 작성한 article 필요 followings = request.user.followings.all() followings = chain(followings, [request.user]) articles = Article.objects.filter(user__in=followings).order_by('-id') context = { 'articles': articles } return render(request, 'articles/index.html', context)<file_sep>from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import update_session_auth_hash from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UserChangeForm, PasswordChangeForm from django.contrib.auth.decorators import login_required from django.contrib.auth import login as auth_login # login함수 from django.contrib.auth import logout as auth_logout from .forms import CustomUserChangeForm, CustomUserCreationForm from .models import User from django.contrib.auth import get_user_model from IPython import embed # Create your views here. def signup(request): if request.user.is_authenticated: # 로그인 상태 확인 return redirect('articles:index') # 로그인이 된 경우 index로 redirect if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save() auth_login(request, user) return redirect('articles:index') else: form = CustomUserCreationForm() context = { 'form': form } return render(request, 'accounts/form.html', context) def login(request): # embed() if request.method == 'POST': form = AuthenticationForm(request, request.POST) # cookie와 session을 request를 통해 넘겨준다. if form.is_valid(): # 로그인 # from IPython import embed # embed() user = form.get_user() # user를 가지고 와서 auth_login(request, user) # login함수에 입력 return redirect(request.GET.get('next') or 'articles:index') # 단축평가 # return redirect('articles:index') else: form = AuthenticationForm() print(form) context = { 'form': form } return render(request, 'accounts/login.html', context) def logout(request): auth_logout(request) return redirect('articles:index') @login_required def update(request): if request.method == 'POST': # 1. 사용자가 보낸 내용을 담아서 form = CustomUserChangeForm(request.POST, instance=request.user) # 2. 검증 if form.is_valid(): form.save() return redirect('articles:index') else: form = CustomUserChangeForm(instance=request.user) return render(request, 'accounts/form.html', {'form': form}) def password_change(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) # 반드시 첫번째 if form.is_valid(): form.save() update_session_auth_hash(request, form.user) # 비밀번호 변경 후 로그아웃되지 않도록 session을 업데이트한다. return redirect('articles:index') else: form = PasswordChangeForm(request.user) return render(request, 'accounts/password_change.html', {'form': form}) def profile(request, account_pk): User = get_user_model() user = get_object_or_404(User, pk=account_pk) context = { 'user_profile' : user } from IPython import embed # embed() return render(request, 'accounts/profile.html', context) from .models import User as customUser def follow(request, account_pk): User = get_user_model() obama = get_object_or_404(User, pk=account_pk) if obama != request.user: # obama를 팔로우한 적이 있다면 if request.user in obama.followers.all(): # 취소 obama.followers.remove(request.user) # 아니면 else: # 팔로우 obama.followers.add(request.user) return redirect('accounts:profile', account_pk) <file_sep># Django - CRUD > Django ORM을 활용하여 게시판 기능 구현하기 ## 1. 환경설정 * 가상환경(venv) * python 3.7.4에서 가상환경 생성 ```bash $ python -V python 3.7.4 $ python -m venv venv ``` * 가상환경 실행 ```bash $ source venv/Scripts/activate (venv) $ ``` * 가상환경 종료 ```bash (venv) $ deactivate ``` * pip - `requirements.txt` 확인 * 현재 패키지 리스트 작성 ```bash $ pip freeze > requirements.txt ``` * 만약, 다른 환경에서 동일하게 설치한다면 ```bash $ pip install -r requiremets.txt ``` * django app - `articles` ## 2. Model 설정 ### 1. `Article` 모델 정의 ```python # articles/models.py class Article(models.Model): title = models.CharField(max_length=10) content = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) ``` * 클래스 정의할 때는 `models.Model` 을 상속받아 만든다. * 정의하는 변수는 실제 데이터베이스에서 각각의 필드(column)을 가지게 된다. * 주요 필드 * `CharField(max_length)` * 필수 인자로 `max_length`를 지정하여야 한다. * 일반적으로 데이터베이스에서 `VARCHAR` 로 지정된다. * `<input type="text">` * `TextField()` * 일반적으로 데이터베이스에서 `TEXT` 으로 지정된다. * `CharField` 보다 더 많은 글자를 저장할 때 사용된다. * `<textarea>` * `DateTimeField()` * 파이썬의 datetime 객체로 활용된다. * 옵션 * `auto_now_add=True` : 생성시에 자동으로 저장(게시글 작성일) * `auto_now=True` : 변경시에 자동으로 저장(게시글 수정일) * `BooleanField()`, `FileField()` , `IntegerField()` 등 다양한 필드를 지정할 수 있다. * `id` 는 자동으로 `INTEGER` 타입으로 필드가 생성되고, 이는 `PK (Primary Key)` 이다. * 모든 필드는 `NOT NULL` 조건이 선언되며, 해당 옵션을 수정하려면 아래와 같이 정의할 수 있다. ```python username = models.CharField(max_length=10, null=True) ``` ### 2. 마이그레이션(migration) 파일 생성 > 마이그레이션(migration)은 모델에 정의한 내용(데이터베이스의 스키마)의 변경사항을 관리한다. 따라서, 모델의 필드 수정 혹은 삭제 등이 변경될 때마다 마이그레이션 파일을 생성하고 이를 반영하는 형식으로 작업한다. ```bash $ python manage.py makemigrations Migrations for 'articles': articles\migrations\0001_initial.py - Create model Article ``` * 만약, 현재 데이터베이스에 반영되어 있는 마이그레이션을 확인하고 싶다면 아래의 명령어를 활용한다. ```bash $ python manage.py showmigrations articles [ ] 0001_initial ``` ### 3. DB 반영(migrate) > 만들어진 마이그레이션 파일을 실제 데이터베이스에 반영한다. ```bash $ python manage.py migrate Operations to perform: Apply all migrations: admin, articles, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK ``` * 만약 특정 app의 마이그레이션 혹은 특정 버전만 반영하고 싶다면 아래의 명령어를 활용한다. ```bash $ python manage.py migrate articles $ python manage.py migrate articles 0001 ``` * 특정 마이그레이션 파일이 데이터베이스에 반영될 때 실행되는 쿼리문은 다음과 같이 확인할 수 있다. ```bash $ python manage.py sqlmigrate articles 0001 BEGIN; -- -- Create model Article -- CREATE TABLE "articles_article" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(10) NOT NULL, "content" text NOT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL); COMMIT; ``` * 데이터베이스에 테이블을 만들 때, 기본적으로 `app이름_model이름` 으로 생성된다. ## 3. Django Query Methods > Django ORM을 활용하게 되면, 파이썬 객체 조작으로 데이터베이스 조작이 가능하다. > > ORM(Object-Relational-Mapping)에서는 주로 활용되는 쿼리문들이 모두 method로 구성 되어있다. ```bash $ python manage.py shell $ python manage.py shell_plus ``` * `shell` 에서는 내가 활용할 모델을 직접 import 해야 한다. ```python from articles.models import Article ``` * `shell_plus` 는 `django_extensions`를 설치 후 `INSTALLED_APPS`에 등록하고 활용해야 한다. ```bash $ pip install django-extensions ``` ```python # crud/settings.py INSTALLED_APPS = [ 'django_extensions', ... ] ``` ### 1. Create ```python # 1. 인스턴스 생성 및 저장 article = Article() article.title = '1번글' article.content = '1번내용' # article = Article(title='글', content'내용') article.save() # 2. create 메서드 활용 article = Article.objects.create(title='글', content='내용') ``` * 데이터베이스에 저장되면, `id` 값이 자동으로 부여된다. `.save()` 호출하기 전에는 `None` 이다. ### 2. Read * 모든 데이터 조회 ```python Article.objects.all() ``` * 리턴되는 값은 `QuerySet` 오브젝트 * 각 게시글 인스턴스들을 원소로 가지고 있다. * 특정(단일) 데이터 조회 ```python Article.objects.get(pk=1) ``` * 리턴되는 값은 `Article` 인스턴스 * `.get()` 은 그 결과가 여러개 이거나 없는 경우 오류를 발생시킴. * 따라서, 단일 데이터 조회시(primary key를 통해)에만 사용한다. * 특정 데이터 조회 ```python Article.objects.filter(title='제목1') Article.objects.filter(title__contains='제목') # 제목이 들어간 제목 Article.objects.filter(title__startswith='제목') # 제목으로 시작하는 제목 Article.objects.filter(title__endswith='제목') # 제목으로 끝나는 제목 ``` * 리턴되는 값은 `QuerySet` 오브젝트 * `.filter()` 는 없는 경우/하나인 경우/여러개인 경우 모두 `QuerySet` 리턴 ### 3. Update ```python article = Article.objects.get(pk=1) article.content = '내용 수정' article.save() ``` * 수정은 특정 게시글을 데이터베이스에서 가져와서 인스턴스 자체를 수정한 후 `save()` 호출. ### 4. Delete ```python article = Article.objects.get(pk=1) article.delete() ``` ### 5. 기타 #### 1. Limiting ```python Article.objects.all()[0] # LIMIT 1 : 1개만 Article.objects.all()[2] # LIMIT 1 OFFSET 2 Article.objects.all()[:3] ``` #### 2. Ordering ```python Article.objects.order_by('-id') # id를 기준으로 내림차순 정렬 Article.objects.order_by('title') # title을 기준으로 오름차순 정렬 ``` ## 4. Namespace를 이용한 단순작업 * `name`키워드를 이용하여 반복작업을 쉽게 할 수 있다. ```python # urls.py app_name = 'articles' # app의 이름 urlpatterns = [ path('', views.index, name='index'), # .... ``` ```python return redirect('articles:detail', article.pk) # url 작성을 한다면 python file 에도 적용 가능하다. ``` ```html ... <form action="{% url 'articles:create' %}" method="POST"> ... ``` * articles - app_name | create - pathname ```html <a href="{% url 'articles:detail' article.pk %}"> ``` * name=detail에 값을 넘겨준다면 넘겨줄 값을 url 뒤에 명시한다. ## 5. GET/POST를 이용한 분기설정 ```python # views.py def create(request): # 저장 로직 if request.method == 'POST': title = request.POST.get('title') content = request.POST.get('content') article = Article(title=title, content=content) article.save() return redirect('articles:detail', article.pk) else: return render(request, 'articles/new.html') ``` * 입력의 `method`에 따라 서로 다른 행동이 가능하다. ```python from django.views.decorators.http import require_POST @require_POST def ..... # .... ``` * POST가 입력되는 경우만 함수가 실행되도록 할 수 있다. ```html <form action="{% url 'articles:update' article.pk%}" method="POST"> <a href="{% url 'articles:detail' article.pk %}"></a> ``` * `<form>`태그는 `GET`과 `POST`를 변경하여 사용할 수 있다. * `<a>`태그는 `GET`으로 고정되어 있다. ## 6.SQL 1:N ### 1. 1:N 관계 생성 ```python from django.db import models # Create your models here. # 1. 모델(스키마) 정의 # 데이터베이스 테이블을 정의하고, # 각각의 컬럼(필드) 정의 class Article(models.Model): # id : integer 자동으로 정의(Primary Key) # id = models.AutoField(primary_key=True) -> Integer 값이 자동으로 하나씩 증가(AUTOINCREMENT) # CharField - 필수인자로 max_length 지정 title = models.CharField(max_length=10) content = models.TextField() # DateTimeField # auto_now_add : 생성시 자동으로 저장 # auto_now : 수정시마다 자동으로 저장 created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.id} : {self.title}' class Comment(models.Model): content = models.CharField(max_length=140) created_at = models.DateTimeField(auto_now_add=True) article = models.ForeignKey(Article, on_delete=models.CASCADE) # on_delete # 1. CASCADE : 글이 삭제되었을 때 모든 댓글을 삭제 # 2. PROTECT : 댓글이 존재하면 글 삭제 안됨 # 3. SET_NULL : 글이 삭제되면 NULL로 치환(NOT NULL일 경우 옵션 사용X) # 4. SET_DEFAULT : 디폴트 값으로 치환. # models.py : python 클래스 정의 # : 모델 설계도 # makemigrations : migration 파일 생성 # : DB 설계도 작성 # migrate : migration 파일 DB 반영 ``` ### 2. 데이터 활용 * 여러 방법으로 데이터 입력이 가능하다. ```python # 1. 직접 입력 a = Article() a.title = '제목1' a.content = '내용1' c = Comment() c.content = '댓글댓글' c.article = a # 객체 직접 저장 c.reporter_id = 1 # 혹은 id를 직접 입력 ``` * 각 객체가 가진 정보를 확인할 수 있다. ```python Article.objects.get(pk=1).comment.content # '댓글댓글' ``` * Foreign key 확인 ```python Article.objects.get(pk=1).comment_set.all() # Article(pk=1)객체를 가진 Comment객체를 모두 표시 ``` ## 7. Model Form ### 1. Model Form 정의 ```python # form.py class ArticleForm(forms.ModelForm): title = forms.CharField( max_length=1, label='제목', widget=forms.TextInput( attrs={ 'placeholder': '제목을 입력바랍니다.' } ) ) content = forms.CharField( # label 내용 수정 label='내용', # Django form에서 HTML 속성 지정 -> widget widget=forms.Textarea( attrs={ 'class': 'my-content', 'placeholder': '내용을 입력바랍니다.', 'row': 5, 'col': 60 } ) ) ``` * 기존에 있는 모델을 form 형식으로 만들어 `HTML`에서 편하게 사용이 가능하다. ```html <!-- article_form이 html로 넘어온 경우 --> <form action="" method='POST'> {% csrf_token %} {{ article_form.as_p }} <button type="submit" class="btn btn-primary">Submit</button> </form> ``` * view.py도 간단하게 만들 수 있다. ```python # views.py def create(request): if request.method == 'POST': # POST 요청 -> 검증 및 저장 로직 article_form = ArticleForm(request.POST) if article_form.is_valid(): # 검증에 성공하면 저장 article = article_form.save() return redirect('articles:detail', article.pk) # else: # return form -> 중복되서 제거 else: # GET 요청 -> Form article_form = ArticleForm() # GET -> 비어있는 Form context # POST -> 검증 실패시 에러메세지와 입력값 다시 context context = { 'article_form': article_form } return render(request, 'articles/form.html', context) ``` ### 2. ModelForm save중 Foreign Key따로 저장하는 방법 ```python # views.py def comment_create(request, article_pk): article = get_object_or_404(Article, pk=article_pk) # 1. modelform에 사용자 입력값 넣고 comment_form = CommentForm(request.POST) # ModelForm instance # 2. 검증 if comment_form.is_valid(): # 3. 맞으면 저장 # 3-1. 사용자 입력값으로 comment instance 생성 (저장 X) comment = comment_form.save(commit=False) # comment object 리턴값 # comment = Comment() # comment.content = request.POST.get('comment_content') # 3-2. Foreign key를 입력하고 저장 comment.article = article comment.save() # 4. return redirect return redirect('articles:detail', article_pk) ``` ### 3. (참고) ModelForm에서 `input`태그의 설정을 변경하는 방법 ```python # ... class MovieForm(forms.ModelForm): open_date = forms.DateField( label = '개봉일', widget = forms.DateInput(attrs={ 'type': 'date'}) ) ``` ## 8. static 설정 ### 1. static을 위한 기본 설정 - 해당 폴더 내부에 해당 파일이 있어야 한다. - `static`설정은 해당 Template에서만 가능하다(Django Template 불러오기는 가능하지 않음) ```python # setting.py # ... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ # static file들을 모두 모아서 해당 URL로 표현된다. (물리 폴더를 뜻하는 것이 아니다.) # /static/boostarap # /static/articles/style.css STATIC_URL = '/static/' # static file 물리 위치 지정 # 기본적으로는 app에 있는 static 폴더들을 모두 관리하며, 아래에 임의의 폴더들을 추가할 수 있다. STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'crud', 'assets') ] # MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage' ``` * static은 기존의 데이터를 사용하는 것으로 요청에 대한 응답만 한다. ```html <!-- ...... --> {% load static %} <link rel="stylesheet" href="{% static 'articles/style.css' %}"> ``` * 같은 방법으로 해당 폴더에 있는 이미지를 불러올 수 있다. ```html <!-- ... --> {% load static %} <img src="{% static 'articles/gom.jpg' %}" class="rounded mx-auto d-block" alt=""> <!-- ... --> ``` ## 9. 서버에 이미지 로드하기 ### 1. 기본 설정 * models.ImageField() 를 사용하기 위해서는 `pillow` 라이브러리가 필요하다. ```bash pip install pillow ``` * `models.py`에 이미지 저장을 위한 공간을 지정한다. ```python # model.py class Article(models.Model): # ... image = models.ImageField() # ... ``` * image저장을 위해 `views.py`에 `request`를 받을 수 있게 설정한다. ```python # views.py def create(request): # ... article.image = request.FILES.get('image') article.save() return redirect('/articles/') # django form을 사용하는 경우 def create(request): if request.method == 'POST': # POST 요청 -> 검증 및 저장 로직 article_form = ArticleForm(request.POST, request.FILES) # POST와 FILES를 받아온다 if article_form.is_valid(): # 검증에 성공하면 저장 article = article_form.save() return redirect('articles:detail', article.pk) ``` * `html`의 `<input>`태그를 이용해 이미지를 받을 수 있다. * 이때, `enctype`를 꼭 설정해주어야 한다. ```python <form action="" method='POST' class="form" enctype="multipart/form-data"> <label for="image">이미지</label> <input type="file" name="image" id="image"> ``` * `setting.py`에 image를 위한 폴더 경로를 설정한다. ```python # setting.py # media file이 실제로 저장되는 파일의 경로 # static 설정과 같다(폴더를 연결해야 이미지를 저장하고 보낼 수 있다.) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ``` * `url.py`에 url을 추가시킨다. **url설정은 꼭 필요하다.** ```python # urls.py from django.conf import settings from django.conf.urls.static import static # .... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ``` * 이미지를 확인하고 싶다면 `html`에서 경로를 연결하여 이미지를 확인할 수 있다. ```html <img src="{{ article.image.url }}" alt="{{article.image.name}} "> ``` ### 2. image의 크기를 조정하여 저장하기 * 이미지 설정을 변경하고 저장하기 위해서는 `imagekit` 라이브러리가 필요하다. ```bash pip install django-imagekit ``` * 사용을 위해서는 `setting.py`에 추가해주어야 한다. ```python # settings.py INSTALLED_APPS = [ # .... 'django_extensions', 'bootstrap4', 'imagekit', ] ``` * 기본 이미지의 크기를 조정하면서 저장이 가능하다. ```python from django.db import models from imagekit.models import ProcessedImageField, ImageSpecField from imagekit.processors import ResizeToFill class Article(models.Model): title = models.CharField(max_length=10) content = models.TextField() image = models.ImageField(blank=True) # ImageSpecField : Input 하나만 받고 처리해서 저장(1개의 이미지를 이용해 처리하여 저장) # ProcessedImageField : Input 받은 것을 처리해서 저장(여러 이미지를 입력받아 처리) # resize to fill : 300 * 300 # resize to fit : 긴쪽을(너비 혹은 높이) 300에 맞추고 비율에 맞게 자름 image_thumbnail = ImageSpecField( # processors=[ResizeToFill(300, 300)], # format='JPEG', # format 옵션 options={'quality': 80} # 압축 퀄리티 ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.id} : {self.title}' ``` * `ImageSpecField`는 폴더에 원본 데이터만 저장하고 요청이 들어오면 해당하는 이미지 처리를 하여 임시 폴더에 저장한다. ```html <img src="{{ article.image.url }}" alt="{{article.image.name}} "> <img src="{{ article.image_thumbnail.url }}" alt="{{article.image_thumbnail.name}} "> ``` ## 10. 회원가입 생성 ### 1. 기존에 존재하는 Model Form 을 이용한 생성방법 ```python # settings.py LOGIN_URL = '/accounts/login' AUTH_USER_MODEL = 'accounts.User' ``` ```python # accounts/views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm # Create your views here. def signup(request): if request.method == 'POST': user_form = UserCreationForm(request.POST) if user_form.is_valid(): user_form.save() return redirect('articles:index') else: user_form = UserCreationForm() context = { 'user_form': user_form } return render(request, 'accounts/signup.html', context) ``` * 기존에 있는 `UserCreationForm`을 이용하면 간단하게 형식을 만들 수 있다. ### 2. Login in 환경 구현 ```python # accounts/views.py from django.contrib.auth.forms import AuthenticationForm def login(request): if request.method == 'POST': form = AuthenticationForm(request, request.POST) # cookie와 session을 request를 통해 넘겨준다. if form.is_valid(): # 로그인 user = form.get_user() # user를 가지고 와서 auth_login(request, user) # login함수에 입력 return redirect('articles:index') else: form = AuthenticationForm() context = { 'form': form } return render(request, 'accounts/login.html', context) ``` * `request`에는 이미 사용자 정보가 들어 있어서 context로 정보를 넘기지 않아도 `user`을 통해 사용할 수 있다. ```html <!--html의 경우 --> <a class="nav-link">{{ user.username }} </a> ``` * Login상태를 확인해주는 메서드가 존재한다. ```python request.user.is_authenticated # request.user 은 현재 로그인한 user의 정보를 보여준다. # 로그인이 되지 않은 경우는 # request는 요청받은 데이터 객체 ``` ```html {% user.is_authenticated %} ``` * 혹은 데코레이터를 사용할 수 있다. ```python from django.contrib.auth.decorators import login_required # ... @login_required def ..... ``` ## 11. 회원정보 변경 ```python # views.py from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UserChangeForm, PasswordChangeForm @login_required def update(request): if request.method == 'POST': # 1. 사용자가 보낸 내용을 담아서 form = CustomUserChangeForm(request.POST, instance=request.user) # 2. 검증 if form.is_valid(): form.save() return redirect('articles:index') else: form = CustomUserChangeForm(instance=request.user) return render(request, 'accounts/form.html', {'form': form}) def password_change(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) # 반드시 첫번째 if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect('articles:index') else: form = PasswordChangeForm(request.user) return render(request, 'accounts/password_change.html', {'form': form}) ``` ## 12. User 기능 ### 1. 장고 User * 장고는 User관련 기능이 내부적으로 있어서 가져다 쓰면 된다. * django.contrib.auth.models.User 를 변경해야 한다면 => 상속받아서 만들면 된다. => DB와 연결되어 있어 다 변경해야 함 => 프로젝트를 만들면서 미리 수행 권장 : Django 추천 => 변경 후 settings 설정의 AUTH_USER_MODEL => User클래스는 get_user_model() settings설정에서 * models.py에서 get_user_model 사용이 힘들다. => 장고 명령어 수행 순서 때문에 사용하지 못할 수 있다. => User 클래스가 아직 없을 수 있다. => 그냥 settings.AUTH_USER_MODEL 을 사용하면 알아서 바꿔준다. * UserCreationForm을 못쓰는 이유 => 실제 내부 코드는 User을 import해서 사용(from django.contrib.auth.models import User) => get_user_model()을 사용하고 상속받아 덮어쓰자 * 프로젝트 시작시 User 모델을 빼자 => User 클래스가 필요하면, get_user_model()을 호출하여 사용하자. => models.py에서만 settings.AUTH_USER_MODEL 을 사용하자. ### 2. User객체를 저장하는 Model 설정 ```python from django.db import models from django.conf import settings class Article(models.Model): # ...... user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # 로그인된 User객체 저장 # settings.AUTH_USER_Model : 'accounts.User'(str) # from django.conf import settings.AUTH_USER_MODEL ``` `from django.conf import settings.AUTH_USER_MODEL` : 현재 로그인된 User class 객체 `from django.contrib.auth import get_user_model` : User class ## 13 .(User) Django Authentication ### `User` Class > django에서는 프로젝트를 시작할 때, 항상 `User`Class를 직접 만드는 것을 추천함! [링크]( https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#substituting-a-custom-user-model ) > > django의 기본 Authentication과 관련된 설정 값들을 활용하기 위해 `accounts` 앱으로 시작하는 것을 추천(ex-LOGIN_URL = '/accounts/login/') 1. `models.py` ```python # accounts/models.py from django.contrib.auth.models import AbstractUser class User(AbstractUser): pass ``` > django 내부에서 `User`를 기본적으로 사용한다. ex) `python manage.py createsuperuser` > > 확장 가능성(변경)을 위해 원하는 앱에 내가 원하는 형식으로 class를 정의 > > `User`상속관계 [Github 링크]( https://github.com/django/django/blob/master/django/contrib/auth/models.py#L384 ) [공식문서링크]( https://docs.djangoproject.com/en/2.2/ref/contrib/auth/#fields ) > > * `AbstractUser` : `username`, `last_name`, `first_name`, `email`, .... > * `AbstractBaseUser`: `password`, `last_login` > * `models.Model` 2. `settings.py` ```python # project/settings.py AUTH_USER_MODEL = 'accounts.User' ``` * `User`클래스를 활용하는 경우에는 `get_user_model()`을 함수를 호출하여 사용한다. ```python # accounts/forms.py from django.contrib.auth import get_user_model class CustomUserChangeForm(UserChangeForm): class Meta: model = get_user_model() # User return fields = ['username', 'first_name', 'last_name'] ``` * 단, `models.py`에서 사용하는 경우에는 `settings.AUTH_USER_MODEL`을 활용한다.[settings]( https://docs.djangoproject.com/en/2.2/ref/settings/#auth-user-model ) ```python # articles/models.py from django.conf import settings class Article(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASECADE) ``` [공식문서-Referencing the `User`model]( https://docs.djangoproject.com/en/2.2/topics/auth/customizing/#referencing-the-user-model) 3. `admin.py` * admin 페이지를 활용하기 위해서는 직접 작성을 해야 한다. * `UserAdmin`설정을 그대로 활용할 수 있다. ```python # accounts/admin.py from django.contrib.auth.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin) ``` ## 14. Authentication Forms ### 1. `UserCreationForm`: ModelForm * custom user를 사용하는 경우 직접 사용할 수 없음. * 실제 코드상에 `User`가 직접 import 되어 있기 때문에[Github 링크]() ```python # accounts/form from django.contrib.auth.forms import UserChangeForm, UserCreationForm from django.contrib.auth import get_user_model class CustomUserChangeForm(UserChangeForm): class Meta: model = get_user_model() # User return fields = ['username', 'first_name', 'last_name'] ``` * `ModelForm`이므로 활용 방법은 동일하다. ### 2. `UserChangeForm`: ModelForm * custom user를 사용하는 경우 직접 사용할 수 없음. * 그대로 활용하는 경우 `User`와 관련된 모든 내용을 수정하게 됨 * 실제 코드상에 필드가 `__all__`로 설정되어 있음. [Github 링크]() ```python from django.contrib.auth.forms import UserChangeForm, UserCreationForm from django.contrib.auth import get_user_model class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('username', 'first_name', 'last_name') ``` ### 3. `AuthenticationForm` * `ModelForm`이 아님! **인자 순서를 반드시 기억하자** * `AuthenticationForm(request, data, .....)` ```python def login(request): if request.method == 'POST': form = AuthenticationForm(request=request, data=request.POST) # cookie와 session을 request를 통해 넘겨준다. if form.is_valid(): # 로그인 # from IPython import embed # embed() user = form.get_user() # user를 가지고 와서 auth_login(request, user) # login함수에 입력 return redirect(request.GET.get('next') or 'articles:index') # 단축평가 # return redirect('articles:index') else: form = AuthenticationForm() print(form) context = { 'form': form } return render(request, 'accounts/login.html', context) ``` * 로그인에 성공한 `user`의 인스턴스는 `get_user()`메소드를 호출하여 사용한다. * 실제 로그인은 아래의 함수를 호출하여야 한다. ```python from django.contrib.auth import login as auth_login auth_login(request, user) ``` ### 4. `PasswordChangeForm` * `ModelForm`이 아님! **인자 순서를 반드시 기억하자** * `PasswordChangeForm(user, data)` ```python if request.method == 'POST': form = PasswordChangeForm(request.user, request.data) else: form = PasswordChangeForm(request.user) ``` * 비밀번호가 변경이 완료된 이후에는 기존 세션 인증 내역이 바뀌어서 자동으로 로그아웃된다. 따라서, 아래의 함수를 호출하면, 변경된 비밀번호로 세션 내역을 업데이트한다. ```python from django.contrib.auth import update_session_auth_hash update_session_auth_hash(request, form.user) ``` ## 15. (참고사항)Appendix.import ```python from django.contrib.auth import login from django.contrib.auth import logout from django.contrib.auth import update_session_auth_hash from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.forms import UserChangeForm from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth.forms import User from django.contrib.auth.forms import AbstractUser from django.contrib.auth.forms import AbstractBaseUser from django.contrib.auth.decorators import login_required ``` ```python from django.conf import settings ``` ```python from django.db import models # models.Model, models.CharField()...... from django import forms # forms.ModelForm, forms.form ``` ```python from django.shortcuts import render, redirect, get_object_or_404 ``` ```python from django.views.decorators.http import require_POST, .... ``` ## 16 .M:N Many to many ### 1. 중개 모델 ```python from django.db import models # Create your models here. class Doctor(models.Model): name = models.TextField() class Patient(models.Model): name = models.TextField() class Reservation(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) ``` 1. 예약 만들기 ```python d1=Doctor.objects.create(name='kim') p1=Patient.objects.create(name='taewoo') Reservation.objects.create(doctor=d1,patient=p1) ``` 2. 1번 환자의 예약 목록 ```python p1.reservation_set.all() ``` 3. 1번 의사의 예약 목록 ```python d1.reservation_set.all() ``` 4. 1번 의사의 환자 목록 * 지금 상태에서 바로 의사가 해당하는 환자들로 접근을 할 수는 없다. ```python for r in d1.reservation_set.all(): print(r.patient) ``` ### 2. 중개 모델(through 옵션) > 의사->환자 혹은 환자->의사로 접근을 하기 위해서는 `ManyToManyField`옵션을 사용한다. > > `Reservation`모델을 활용하려면 `through`옵션을 사용한다. > > `through`옵션이 없으면, 기본적으로 `APPNAME_patient_doctor` 테이블을 생성한다. ```python from django.db import models # Create your models here. class Doctor(models.Model): name = models.TextField() class Patient(models.Model): name = models.TextField() doctors = models.ManyToManyField(Doctor, through='Reservation') class Reservation(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) ``` * 마이그레이션 파일을 만들거나 마이그레이트 할 필요가 없다. * 즉, 데이터베이스는 전혀 변경되는 것이 없다. 1. 1번 의사의 예약 목록 ```python d1.reservation_set.all() ``` 2. 1번 의사의 환자 목록 > `Doctor`는 `Patient`의 역참조이므로, `naming convention`에 따라 아래와 같이 접근 ```python d1.patient_set.all() ``` 3. 1번 환자의 의사 목록 * `Patient`는 `Doctor`의 직접참조(`Doctor`)이므로, 아래와 같이 접근 ```pyhon p1.doctors.all() ``` #### 2.1 `related_name` ```python from django.db import models # Create your models here. class Doctor(models.Model): name = models.TextField() class Patient(models.Model): name = models.TextField() doctors = models.ManyToManyField(Doctor, through='Reservation', related_name='patients') class Reservation(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) ``` * 역참조시 `related_name`옵션으로 직접 설정할 수 있다. * 설정하지 않으면 기본적으로 `Model명_set`으로 된다. * 반드시 설정할 필요는 없지만, 필수적인 상황이 발생할 수 있다. * ex) `User` - `Article` * 따라서, `ManyToManyField`를 쓸 때에는 항상 `related_name`을 설정하고, 모델의 복수형으로 표기하자. 1. 1번 의사의 환자 목록 ```python d1.patients.all() ``` ### 3. 중개모델 없이 작성 ```python from django.db import models # Create your models here. class Doctor(models.Model): name = models.TextField() class Patient(models.Model): name = models.TextField() doctors = models.ManyToManyField(Doctor, related_name='patients') ``` * `앱이름_patient_doctors`로 테이블이 자동으로 생성된다. * 별도의 컬럼이 필요 없는 경우는 위와 같이 작성한다. * 만약, 예약시 추가정보(ex - 시간, 담당자 ....)를 담기 위해서라면 반드시 중개 모델이 필요하다. 1. 예약 생성 ```python d2 = Doctor.objects.create(name='kim') p2 = Patient.objects.create(name='hwang') d2.patients.add(p2) ``` 2. 예약 취소 ```python d2.patients.remove(p2) ``` ## 17. 좋아요 구현 ```python user.like_articles.all() # related_name (M2M) # => Queryset (article instance 담겨있음) user.article_set.all() # related_name X (FK 1:N) # => Queryset (article instance 담겨있음) article.user # FK(1:N) # => article을 작성한 user instance article.like_users.all() # M2M # => Queryset article에 좋아요를 한 ``` ```html {{article.like_user.count}} 댓글수 {{article.comment_set.all()}} ``` ## 18. 소셜 로그인(OAuth-인증체계) ### 1. auth 설정 * authentication(인증 - 로그인) * authorization(권한 - 로그인 이후) ```bash $ pip install django-allauth ``` ```python # settings.py ..... # django-allauth AUTHENTICATION_BACKENDS = ( # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', ) # 나머지는 https://django-allauth.readthedocs.io/en/latest/installation.html에서 확인 가능 ``` 카카오 설정 후 * admin -> 소셜 어플리캐이션 -> 클라이언트 id: REST API. 비밀 키: SECRET KEY * [social accounts templates추가]( https://django-allauth.readthedocs.io/en/latest/templates.html ) ```html {% load socialaccount %} <a href="{% provider_login_url "kakao" %}">kakao 로그인</a> ``` > 1. 사용자는 카카오링크(/accounts/kakao/login/) > 2. 사용자는 카카오 사이트 로그인 페이지를 확인 > 3. 사용자는 로그인 정보를 카카오로 보냄 > 4. 카카오는 redirect url로 django 서버로 사용자 토큰을 보냄 > 5. 해당 토큰을 이용하여 카카오에 인증 요청 > 6. 카카오에서 확인 > 7. 로그인 > > ----------------------------------------------------------- > > 토큰(access token)은 유효기간이 있는데, refresh token을 통해서 토큰 재발급을 받을 수 있다. > > **카카오** - 리소스 서버/인증 서버 > > **사용자(리소스 owner)** - 유저 > > **django** - 클라이언트 ## 참고 ### model IntegerField에 제한된 숫자 입력하기 ```python from django.core.validators import MinValueValidator, EmailValidator from django import models class Person(models.Model): age = models.IntegerField(validators=[MinValueValidator(20, message='미성년자 출입금지')]) email = models.CharField(max_length=120, validators=[EmailValidator(message='이메일 형식이 아닙니다.')]) ``` * 데이터 입력 후 검증시 validators에 있는 message를 출력하며 에러 발생 * 혹은 validators에 내가 만든 함수를 넣어도 된다.[Validator django공식문서 확인]( https://docs.djangoproject.com/en/2.2/ref/validators/ ) ### 나와 내 친구들이 작성한 글 확인하기 * 내 친구들이(request.user.followings) 작성한 것 + 내가(request.user) 작성한 article 필요 ```python def explore(request): my_articles = request.user.article_set.all() my_friends = request.user.followings.all() return render(request, 'articles/explore.html', {'my_articles': my_articles, 'my_friends': my_friends}) ```
ca346f3b319e210e58aa426dc966e1c1f0aaebc2
[ "Markdown", "Python" ]
5
Markdown
ByeongjunCho/django-crud
14229be53bd2e0a3e0db7ec5c706e681ed8bdbdb
57a2c454355ed5ce524134d93617286cec3e8cbc
refs/heads/master
<repo_name>kyungseop/es-tool<file_sep>/src/test/resources/sample.sh #!/bin/bash ## keyword 로 삭제 if [ -z $1 ]; then echo "Usage: es_index_delete_by_seq.sh keyword" exit 1; fi echo "delete index keyword:$1" echo "" data="{ \"query\": { \"term\": { \"keyword\": \"$1\" } } }" out="curl -X POST \"localhost:9200/index/_delete_by_query\" -H \"Content-Type: application/json\" -d '$data'" echo "out=$out" echo $out > run.sh chmod 755 run.sh ./run.sh echo "" <file_sep>/src/test/resources/sample2.sh #!/bin/bash if [ -z $1 ] || [ -z $2 ] || [ -z $3 ]; then echo "Usage: sample2.sh seq id name" echo " sample2.sh 1 super tony" exit 1; fi echo "update application keyword:$1 , $2 , $3" echo "" data="{ \"script\": { \"inline\": \"ctx._source.user.id = \u0027$2\u0027 ; ctx._source.user.name = \u0027$3\u0027 \", \"lang\": \"painless\" }, \"query\": { \"term\": { \"keyword\": \"$1\" } } }" out="curl -X POST \"localhost:9200/index/_update_by_query\" -H \"Content-Type: application/json\" -d '$data'" echo "out=$out" echo $out > run.sh chmod 755 run.sh ./run.sh echo "" <file_sep>/src/main/resources/application.properties spring.freemarker.enabled=true spring.freemarker.suffix=.ftl spring.freemarker.cache=false spring.freemarker.charset=utf-8 spring.freemarker.template-loader-path=classpath:/templates spring.devtools.livereload.enabled=true <file_sep>/src/main/java/com/elasticsearch/tool/common/Constants.java package com.elasticsearch.tool.common; public class Constants { public static final String WHITE_SPACE = " "; public static final String OR = " || "; public static final String NEW_LINE = "\n"; public static final String PRETTY = "?pretty"; public static final String URL_TEMPLATE = "curl -X %s \"%s/%s\" -H \"Content-Type: application/json\" -d '$data'"; public static final String PREFIX = "$"; public static final String HEADER_FORMAT = "if %s; then"; public static final String PARAM_FORMAT = "[ -z %s ]"; } <file_sep>/src/main/java/com/elasticsearch/tool/controller/HomeController.java package com.elasticsearch.tool.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import java.io.IOException; import java.util.HashMap; import java.util.List; import static com.elasticsearch.tool.util.EsQueryUtils.makeEsQueryToShell; @Slf4j @Controller public class HomeController { @GetMapping("/") public ModelAndView hello(ModelAndView mv) { mv.setViewName("home"); return mv; } /** * elasticsearch query to shell script * * @param query query dsl from kibana * @param ip elasticsearch ip address * @return * @throws IOException */ @GetMapping("/convert") public ResponseEntity convert(@RequestParam String query, @RequestParam(required = false) String ip, @RequestParam(required = false) List<String> param, @RequestParam(required = false) String filename) throws IOException { log.info("request to convert => query : {}, ip : {}, param : {}, filename : {}", query, ip, CollectionUtils.isEmpty(param) ? "" : param, filename); String shell = makeEsQueryToShell(query, ip, param, filename); HashMap<String, String> hm = new HashMap<>(); hm.put("before", query); hm.put("after", shell); return ResponseEntity.ok(hm); } } <file_sep>/src/test/java/com/elasticsearch/tool/SimpleTest.java package com.elasticsearch.tool; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static com.elasticsearch.tool.common.Constants.NEW_LINE; import static com.elasticsearch.tool.util.EsQueryUtils.*; @Slf4j public class SimpleTest { @Test public void testCli() throws IOException { //TODO 입력값 : es 주소, 파라미터 N 개 (N개 모두 필수) //TODO 사용방법을 표시해야한다 //TODO replace 할 파라미터 표시 String inputQuery = "GET _search\n" + "{\n" + " \"query\": {\n" + " \"match_all\": {}\n" + " }\n" + "}"; String ip = "localhost:9200"; List<String> queryParams = new ArrayList<>(); queryParams.add("seq"); queryParams.add("id"); queryParams.add("name"); queryParams.add("name"); String shell = makeEsQueryToShell(inputQuery, ip, queryParams, "es.sh"); log.info("testCli => shell : {}", shell); createShellAsFile(shell, "es.sh"); } @Test public void testCreateParameterHeader() throws IOException { List<String> queryParams = new ArrayList<>(); queryParams.add("seq"); queryParams.add("id"); queryParams.add("name"); queryParams.add("name"); String filename = "temp.sh"; String header = createHeader(queryParams, filename); log.info(NEW_LINE + "{}", header); } } <file_sep>/README.md # TODO list - kibana 에서 생성된 쿼리를 shell script 형태로 변환 - shell script 형태로 변환된 내용을 파일로 다운로드 <file_sep>/es.sh #!/bin/bash if [ -z $1 ] || [ -z $2 ] || [ -z $3 ] || [ -z $4 ]; then echo "Usage: ./es.sh seq id name name" exit 1; f1 data="{ \"query\": { \"match_all\": {} } } " out="curl -X GET \"localhost:9200/_search?pretty\" -H \"Content-Type: application/json\" -d '$data'" echo "out=$out" echo $out > run.sh chmod 755 run.sh ./run.sh echo ""<file_sep>/src/main/docs/setting.md Freemaker reload 설정 - build.gradle > dependencies > compile('org.springframework.boot:spring-boot-starter-freemarker') 추가 - build.gradle > dependencies > compile("org.springframework.boot:spring-boot-devtools") 추가 - Intellij > Preferences > Build, Execution, Deployment > Compiler > Build project automatically 체크 후 OK - Intellij > Help > Find Action > Registry 입력 > compiler.automake.allow.when.app.running 체크 후 Close - application.properties 수정 - spring.devtools.livereload.enabled=true - spring.freemarker.cache=false - 사용중인 브라우저의 캐시삭제 Lombok 설정 - build.gradle > dependencies > compileOnly('org.projectlombok:lombok') 추가 - Intellij > Preferences > Build, Execution, Deployment > Compiler > Annotation Processors > Enable annotation processing 체크 후 OK<file_sep>/src/main/java/com/elasticsearch/tool/util/EsQueryUtils.java package com.elasticsearch.tool.util; import lombok.extern.slf4j.Slf4j; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import static com.elasticsearch.tool.common.Constants.*; import static java.util.Objects.requireNonNull; import static org.apache.commons.text.StringEscapeUtils.escapeJava; @Slf4j public class EsQueryUtils { /** * convert qdsl from kibana to shell script * * @param qdsl elasticsearch query from kibana * @param ip elasticsearch ip address * @param params script parameters * @param filename filename * @return qdsl shell script * @throws IOException */ public static String makeEsQueryToShell(final String qdsl, String ip, List<String> params, String filename) throws IOException { requireNonNull(qdsl, "elasticsearch query was required."); if (StringUtils.isEmpty(ip)) { ip = "localhost:9200"; } String[] split = qdsl.split(NEW_LINE); StringBuilder urlBuilder = new StringBuilder(); StringBuilder dataBuilder = new StringBuilder(); boolean firstLine = true; for (String line : split) { if (firstLine) { String[] header = line.split(WHITE_SPACE); try { String format = String.format(URL_TEMPLATE, header[0], ip, header[1] + PRETTY); urlBuilder.append(escapeJava(format)); } catch (ArrayIndexOutOfBoundsException e) { log.error("makeEsQueryToShell => error : {}", e); throw new IllegalArgumentException("error.qdsl.malformed.url"); } firstLine = false; continue; } dataBuilder.append(escapeJava(line)); dataBuilder.append(NEW_LINE); } if (!CollectionUtils.isEmpty(params)) { String header = createHeader(params, filename); return createScript(dataBuilder.toString(), urlBuilder.toString(), header); } else { return createScript(dataBuilder.toString(), urlBuilder.toString()); } } private static String createScript(String escapeData, String escapeUrl) { return createScript(escapeData, escapeUrl, null); } /** * combine each script parts * * @param escapeData qdsl * @param escapeUrl qdsl url & index * @param header script parameters and usage * @return shell script */ private static String createScript(String escapeData, String escapeUrl, String header) { log.debug("createScript => escapeUrl : {}", escapeUrl); log.debug("createScript => escapeData : {}", escapeData); StringBuilder scriptBuilder = new StringBuilder(); scriptBuilder.append("#!/bin/bash"); scriptBuilder.append(NEW_LINE); scriptBuilder.append(NEW_LINE); scriptBuilder.append(NEW_LINE); if (!StringUtils.isEmpty(header)) { scriptBuilder.append(header); scriptBuilder.append(NEW_LINE); scriptBuilder.append(NEW_LINE); scriptBuilder.append(NEW_LINE); } scriptBuilder.append("data=\"" + escapeData + "\""); scriptBuilder.append(NEW_LINE); scriptBuilder.append("out=\"" + escapeUrl + "\""); scriptBuilder.append(NEW_LINE); scriptBuilder.append("echo \"out=$out\""); scriptBuilder.append(NEW_LINE); scriptBuilder.append("echo $out > run.sh"); scriptBuilder.append(NEW_LINE); scriptBuilder.append("chmod 755 run.sh"); scriptBuilder.append(NEW_LINE); scriptBuilder.append("./run.sh"); scriptBuilder.append(NEW_LINE); scriptBuilder.append(" echo \"\""); return scriptBuilder.toString(); } /** * create shell script parameter and usage * * @param scriptParameters script parameters * @param filename script filename * @return parameter and usage string */ public static String createHeader(List<String> scriptParameters, String filename) { if (StringUtils.isEmpty(filename)) { filename = "es.sh"; } List<String> params = new ArrayList<>(); for (int i = 1; i <= scriptParameters.size(); i++) { params.add(String.format(PARAM_FORMAT, PREFIX + i)); } String delimitedString = StringUtils.collectionToDelimitedString(params, OR); String headerParams = String.format(HEADER_FORMAT, delimitedString); String usageSequence = StringUtils.collectionToDelimitedString(scriptParameters, WHITE_SPACE); StringBuilder headerBulder = new StringBuilder(); headerBulder.append(headerParams); headerBulder.append(NEW_LINE); headerBulder.append("echo \"Usage: ./" + filename + " " + usageSequence + "\""); headerBulder.append(NEW_LINE); headerBulder.append("exit 1;"); headerBulder.append(NEW_LINE); headerBulder.append("f1"); return headerBulder.toString(); } /** * @param shellScript shell script * @param filename script filename * @throws IOException */ public static void createShellAsFile(String shellScript, String filename) throws IOException { FileWriter fileWriter = new FileWriter(filename); PrintWriter printWriter = new PrintWriter(fileWriter); printWriter.print(shellScript); printWriter.close(); } }
20d0c6b8a182fea2269444971efffde0a808e70b
[ "Java", "INI", "Markdown", "Shell" ]
10
Shell
kyungseop/es-tool
ce9d6897529f38dd72b536a4c1a9868e48dc5ab9
b73252a40d6aa7fe862dc1bf837a6a609daf61dc
refs/heads/main
<file_sep>import React, { Component } from 'react' import { Text, View,Image,StyleSheet,TouchableOpacity,StatusBar} from 'react-native' import {Icon} from 'react-native-elements' import {NavigationContainer} from '@react-navigation/native' import {createDrawerNavigator} from '@react-navigation/drawer' import {createStackNavigator} from '@react-navigation/stack' import {createMaterialBottomTabNavigator} from '@react-navigation/material-bottom-tabs' import LinearGradient from 'expo-linear-gradient'; import Connexion from './component/Connexion' import HomeScreen from './component/HomeScreen' import Profils from './component/Profils' import Notification from './component/Notification' const Drawer = createDrawerNavigator(); const Stack = createStackNavigator(); const BottomTabs = createMaterialBottomTabNavigator(); const Home =({navigation})=>{ return( <View style={styles.container}> <StatusBar barStyle={'light-content'} backgroundColor={'transparent'} translucent /> <View style={{flex: 1,alignItems:'center',justifyContent:'center'}}> <View style={styles.containerImage}> <Image source={require('./assets/logo_uac2.png')} resizeMode="cover" style={styles.image}/> </View> <View style={{marginVertical: 60}}> <TouchableOpacity style={styles.button} onPress={()=>navigation.navigate('Connexion')}> <Text style={{color:'white',fontWeight:'bold',fontSize:20}}>Commencer</Text> </TouchableOpacity> </View> </View> </View> ) } class App extends Component { render() { bottomTabNav =()=>{ return( <BottomTabs.Navigator> <BottomTabs.Screen name="HomeScreen" component={HomeScreen} options={{tabBarColor: '#128800',tabBarIcon:() => <Icon size={ 20 } name={ 'home' } color={ 'white' }/> }}/> <BottomTabs.Screen name="Notification" component={Notification} options={{tabBarColor: '#128800',tabBarIcon:() => <Icon size={ 20 } name={ 'comment' } color={ 'white' }/> }}/> <BottomTabs.Screen name="Profils" component={Profils} options={{tabBarColor: '#128800',tabBarIcon:() => <Icon size={ 20 } name={ 'person' } color={ 'white' }/> }}/> </BottomTabs.Navigator> ) } return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name="Home" component={Home} options={{headerShown: false,}}/> <Stack.Screen name="Connexion" component={Connexion} options={{headerShown: false,}} /> <Stack.Screen name="HomeScreen" children={bottomTabNav} options={{headerShown: false,}}/> </Stack.Navigator> </NavigationContainer> ) } } const styles = StyleSheet.create({ container: { flex: 1, alignItems:'center', justifyContent: 'center', backgroundColor: '#128800' }, containerImage: { width: 200, height: 205, marginVertical: 80 }, image: { width:'100%', height:'100%', }, button: { justifyContent: 'center', alignItems: 'center', width: 250, height: 50, elevation: 3, backgroundColor: 'red', borderRadius: 5 , } }) export default App
63afc4e36d8cdd0e91e9f77f83272702e04a0d71
[ "JavaScript" ]
1
JavaScript
Norlan-20/JOB-UAC-Mobile
e813bb31420bc2445984622370967f3c0c8c4a51
ab9608b0c69dbe947e0ba680e1ca5d9b414dc013
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.papn; import javax.inject.Named; import javax.enterprise.context.RequestScoped; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; import javax.servlet.http.Part; /** * * @author <NAME> */ @Named(value = "manifestFileUploadbean") @RequestScoped public class ManifestFileUploadbean { private Part uploadedManifestFile; private String message; /** * Creates a new instance of ManifestFileUploadbean */ public ManifestFileUploadbean() { } /** * @return the uploadedManifestFile */ public Part getUploadedManifestFile() { return uploadedManifestFile; } /** * @param uploadedManifestFile the uploadedManifestFile to set */ public void setUploadedManifestFile(Part uploadedManifestFile) { this.uploadedManifestFile = uploadedManifestFile; } /** * @return the message */ public String getMessage() { return message; } /** * @param message the message to set */ public void setMessage(String message) { this.message = message; } public void upload() { if (null != uploadedManifestFile) { try { InputStream is = uploadedManifestFile.getInputStream(); message = new Scanner(is).useDelimiter("\\A").next(); setMessage(uploadedManifestFile.getSubmittedFileName()); System.out.println(getMessage()); } catch (IOException ex) { } } } }
f9b9bcc2c320a35ba36c0d938e02a7925cd54117
[ "Java" ]
1
Java
calvino-git/ManifestValidation
01d9525cbd5f165f809a9455c5ccb82f164cc59b
909c3cf06afac8c46d186488e234b6d7454dd509
refs/heads/master
<repo_name>greenspector/greenspector-meter-api-xamarin-examples<file_sep>/CreditCardValidator.Droid.UITests/Tests.cs using NUnit.Framework; using Xamarin.UITest; using Xamarin.UITest.Android; namespace CreditCardValidator.Droid.UITests { [TestFixture] public class Tests { AndroidApp app; [SetUp] public void BeforeEachTest() { app = ConfigureApp.Android.InstalledApp("com.xamarin.example.creditcardvalidator").StartApp(); //Greenspector Measure Set Up app.Invoke("SetUpMeasureBackdoor", "[Put your Greenspector TOKEN]"); } [Test] public void CreditCardNumber_TooShort_DisplayErrorMessage() { //Start of Greenspector measure app.Invoke("StartMeasureBackdoor"); app.WaitForElement(c => c.Marked("action_bar_title").Text("Enter Credit Card Number")); app.EnterText(c => c.Marked("creditCardNumberText"), new string('9', 15)); app.Tap(c => c.Marked("validateButton")); app.WaitForElement(c => c.Marked("errorMessagesText").Text("Credit card number is too short.")); //Stop of Greenspector measure app.Invoke("StopMeasureBackdoor","TestBackdoor"); } } } <file_sep>/README.md # greenspector-meter-api-xamarin-examples Integration of Greenspector Probe in Xamarin UI Tests <file_sep>/CreditCardValidator.Droid/MainActivity.cs using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using CreditCardValidation.Common; using System.Threading; /*Needed references (need to be integrate in References*/ using Com.Greenspector.Probe.Android.Interfaces; using Java.Interop; namespace CreditCardValidator.Droid { [Activity(Label = "@string/activity_main", MainLauncher = true, Theme = "@android:style/Theme.Holo.Light")] public class MainActivity : Activity { /*Greenspector Backdoor method to call on Xamarin.UITests*/ Api gspt; [Export("SetUpMeasureBackdoor")] public void SetUpMeasureBackdoor(String token) { gspt = new Api(); // CHANGE PARAMETERS ThreadPool.QueueUserWorkItem(o => gspt.SetUpMeasure(ApplicationContext, new String[] { "com.xamarin.example.creditcardvalidator" }, null, "XamarinCreditCard", "1", "https://app.greenspector.com/api", token, 180, 200, true)); } [Export("StartMeasureBackdoor")] public void StartMeasureBackdoor() { gspt.StartMeasure(); } [Export("StopMeasureBackdoor")] public void StopMeasureBackdoor(String TestName) { ThreadPool.QueueUserWorkItem(o => gspt.StopMeasure(TestName)); } /*End of Greenspector Backdoor*/ static readonly ICreditCardValidator _validator = new SimpleCreditCardValidator(); EditText _creditCardTextField; TextView _errorMessagesTextField; Button _validateButton; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); _errorMessagesTextField = FindViewById<TextView>(Resource.Id.errorMessagesText); _creditCardTextField = FindViewById<EditText>(Resource.Id.creditCardNumberText); _validateButton = FindViewById<Button>(Resource.Id.validateButton); _validateButton.Click += (sender, e) =>{ _errorMessagesTextField.Text = String.Empty; string errMessage; if (_validator.IsCCValid(_creditCardTextField.Text, out errMessage)) { var i = new Intent(this, typeof(CreditCardValidationSuccess)); StartActivity(i); } else { RunOnUiThread(() => { _errorMessagesTextField.Text = errMessage; }); } }; } } }
99bc72492982c88f9b59b86e4851cb1278172d10
[ "Markdown", "C#" ]
3
C#
greenspector/greenspector-meter-api-xamarin-examples
6a927da9e955cbf6701946ad51c171ae5a74a3f5
c05b499a25e50cb53729f461f4466a54f2890b39
refs/heads/realMaster
<file_sep>DROP DATABASE IF EXISTS tranquil_db; CREATE DATABASE tranquil_db; USE tranquil_db; CREATE TABLE user_info ( id INT AUTO_INCREMENT NOT NULL, username VARCHAR (30), password VARCHAR (45), name VARCHAR (45), score INT (10), meditationvid VARCHAR(300), exercisevid VARCHAR(300), PRIMARY KEY (id) ); CREATE TABLE data_output ( id INT AUTO_INCREMENT NOT NULL, category VARCHAR (45), min INT (10), max INT (10), meditation VARCHAR (45), exercise VARCHAR (45), description VARCHAR (300), PRIMARY KEY (id) );<file_sep>var connection = require("./connection.js"); function printQuestionMarks(num) { // create an empty array var arr = []; // We count the amount of ? we will need for a SQL query for (var i = 0; i < num; i++) { arr.push("?"); } // We create a string out of the array return arr.toString(); } // Helper function to convert object key/value pairs to SQL syntax function objToSql(ob) { var arr = []; // loop through the keys and push the key/value as a string int arr for (var key in ob) { var value = ob[key]; // check to skip hidden properties if (Object.hasOwnProperty.call(ob, key)) { // if string with spaces, add quotations (Lana Del Grey => 'Lana Del Grey') if (typeof value === "string" && value.indexOf(" ") >= 0) { value = +"''" + value + "''"; } // e.g. {name: '<NAME>'} => ["name='<NAME>'"] // e.g. {sleepy: true} => ["sleepy=true"] arr.push(key + " = " + "'" + value + "'"); console.log(arr); } } // translate array of strings to a single comma-separated string return arr.toString(); } // We create an object with methods to do our SQL injections var orm = { // The first method is read, which we will use to read a table in the database all: function(table, cb) { // We create our query with a parameter of table which will be inputted in the model var queryString = "SELECT * FROM " + table; console.log(queryString); // We run the query and store the result it into a callback function connection.query(queryString, function(err, result) { if (err) throw err; cb(result); }); }, // The second method lets us select specific columns from a SQL table selectColumn: function(tableName, col, cb) { var queryString = "SELECT " + col.toString(); queryString += " FROM " + tableName; console.log(queryString); connection.query(queryString, function(err, result) { if (err) throw err; cb(result); }); }, selectValue: function(tableName, col, val, cb) { var queryString = "SELECT " + col.toString(); queryString += " FROM " + tableName; queryString += " WHERE " + val; console.log(queryString); connection.query(queryString, function(err, result) { if (err) throw err; cb(result); }); }, // The third method is the create function which inputs new data into the database create: function(table, col, val, cb) { var queryString = "INSERT INTO " + table; queryString += " ("; queryString += col.toString(); queryString += ") "; queryString += "VALUES ("; queryString += printQuestionMarks(val.length); queryString += ") "; console.log(queryString); connection.query(queryString, val, function(err, result) { if (err) throw err; cb(result); }); }, // The last method is the update method where we update values inside the database update: function(table, input, val, cb) { var queryString = "UPDATE " + table; queryString += " SET "; queryString += objToSql(input); queryString += " WHERE "; queryString += val; console.log(queryString); connection.query(queryString, function(err, result) { if (err) throw err; cb(result); }); } }; // We make the ORM object available for other files to require module.exports = orm; <file_sep>//When we click the register submit button, we will check for userId and password requirements// var userInfo; //=============Registration Code ================== /*/This makes an ajax post request to tranquilController. The controller will validate the userInfo object meets our account creation requirements. If successful, we'll redirect to /survey, if not, we'll display an error message/*/ $("#register-submit").on("click", function(event) { console.log("clicked"); event.preventDefault(); $(".input-field").trigger("reset"); userInfo = { name: $("#input-username").val(), userId: $("#input-userID").val(), password: $("#input-<PASSWORD>").val() }; console.log("before ajax post"); $.ajax("/api/registration", { type: "POST", data: userInfo }).then(function(err, response) { if (err) { $("small").text(err); } else window.location.href = "/survey"; }); }); //=============Login Code ================== /*/ Here we make another ajax POST request The controller will validate loginInput object has matching userId and password. If successful, we'll redirect to /survey, if not, we'll display an error message/*/ $("#login-submit").on("click", function(event) { console.log("clicked login"); event.preventDefault(); var loginInput = { userId: $("#userId").val(), password: $("#<PASSWORD>").val() }; console.log(loginInput); $.ajax("/api/login", { type: "POST", data: loginInput }).then(function(err, response) { console.log("sending login info for validation"); //if the controller verifies the login information as correct we will reload to /survey" if (err) { $("#error-login").text(err); } else window.location.href = "/result"; }); }); //=============Survey Code ================== /*/ Here we make another ajax POST request where we send over the user's score, and wait for a response /*/ function scoreCalculator(userInput) { var score = 0; for (let i = 0; i < userInput.data.length; i++) { score += userInput.data[i]; } console.log({ score }); // assessment(userInput, score); } // scoreCalculator(userInput); function assessment(userInput, score) { console.log({ userInput }); console.log(userInput.category); // create cases where we check the scores with the corresponding database tables // each case will start a function that will return a random input video in the category set in the switch case switch (userInput.category) { case "meditation": // set a function to work out a random meditation video in the stress level coming from the score meditation(score); break; case "yoga": // set a function to work out a random yoga video in the stress level coming from the score yoga(score); break; case "exercise": // set a fucntion to work out a random exercise video in the stress level coming from the score exercise(score); break; } } // this function takes the score and then function meditation(data) { console.log(data); } function yoga(data) { console.log(data); } function exercise(data) { console.log(data); } <file_sep>// We require both the models var userInfo = require("../models/user_info"); var dataOutput = require("../models/data_output"); var path = require("path"); // We require the express module var express = require("express"); // We require the Router method from express var router = express.Router(); var id = []; // HTML ROUTES // ---------------------------------------------------------------------- // We set the route for our home page router.get("/", function(req, res) { res.sendFile(path.join(__dirname, "../views/main.html")); }); // We set the route for our survey page router.get("/survey", function(req, res) { res.sendFile(path.join(__dirname, "../views/survey.html")); }); // We set the route to our results page router.get("/result", function(req, res) { // we grab the last user from the user_info table var check = true; userInfo.all(function(result) { // we store it into a container var user = result.pop(); console.log(user.meditationvid); console.log(user.exercisevid); // If the user already has video's in his data row, we don't add new ones. if (user.meditationvid !== null && user.exercisevid !== null) { check = false; console.log(check); dataOutput.all(function(result) { renderPage(user, result); }); } else { // We grab the video's from the data_output table dataOutput.all(function(result) { // We set both the values as parameters for our invoked function so we can manipulate the data for our own use renderResult(user, result); }); } }); // We create the function with parameters function renderResult(user, result) { // We check the current user's score (last Id in the list) var userScore = user.score; // We create empty arrays to store the video id's into var meditation = []; var exercise = []; var description = []; // we run through all the data in the data_output table (the video's) for (let i = 0; i < result.length; i++) { // We grab the minimal and maximum scores for each of the video's var min = result[i].min; var max = result[i].max; // We check whether the users score is inbetween the min and max of any of the video's if (userScore >= min && userScore <= max) { // We then store the video's that match the userscore into a mediation and exercise container meditation.push(result[i].meditation); exercise.push(result[i].exercise); description.push(result[i].description); } } // We randomly select one of the meditation and one of the exercise video var medRandom = Math.floor(Math.random() * meditation.length); var exerRandom = Math.floor(Math.random() * meditation.length); // Store those in containers var medId = meditation[medRandom]; var descId = description[medRandom]; var exeId = exercise[exerRandom]; // This is the current users id var id = user.id; var hbsobj = { description: descId, meditation: medId, exercise: exeId, user: user }; // and into the user_info table so that they are connected to the user // This is for reusability of the video's when the user log's back in userInfo.update( { meditationvid: medId, exercisevid: exeId }, ["id =" + id], function(result) { // console.log({ result }); renderPage(hbsobj); } ); console.log(hbsobj); // console.log(user); } // We store all the info we want to send off to the HTML/Handlebars page in an object // We render the page with the object in it. function renderPage(currentUser, result) { if (check) { res.render("result", currentUser); } else { // If we chose to log back in, we grab the description from the database var description = []; for (let i = 0; i < result.length; i++) { if (result[i].meditation.indexOf(currentUser.meditationvid) !== -1) { // push it into an empty array description.push(result[i].description); } } // Put it inside our object var hbsobj = { meditation: currentUser.meditationvid, exercise: currentUser.exercisevid, user: currentUser, description: description }; console.log({ hbsobj }); // that we send over to the results.handlebars page res.render("result", hbsobj); } } }); // API ROUTES // ---------------------------------------------------------------------- // This is the post request for the registration router.post("/api/registration", function(req, res) { var userProfile = req.body; console.log("in the post route"); console.log(req.body); console.log("userProfile" + userProfile); userInfo.all(function(response) { var existingUsernamesArray = []; var object = { data: response }; var registerInfo = object.data; console.log("test"); console.log(registerInfo); console.log(JSON.stringify(object)); for (var i = 0; i < registerInfo.length; i++) { existingUsernamesArray.push(registerInfo[i].username); } console.log("array" + existingUsernamesArray); if ( existingUsernamesArray.includes(userProfile.userId) === false && userProfile.password.length >= 8 && userProfile.password.length <= 20 ) { // ---------------------------------------------------------------------- // Here we connect to the database using the ORM and sending all the data to the table userInfo.create( ["username", "<PASSWORD>", "name"], [userProfile.userId, userProfile.password, userProfile.name], function(result) { // We get back the ID of the user so we can match the score from the survey with the username password id = result.insertId; console.log({ id }); } ); res.status(200).end(); } else if ( existingUsernamesArray.includes(userProfile.userId) === true && userProfile.password.length >= 8 && userProfile.password.length <= 20 ) { var error = "This userId is already taken. Please enter another userId."; res.send(error); } else if (userProfile.name === "") { var error = "Please enter your name"; res.send(error); } else if (userProfile.userId === "") { var error = "Please enter a userId"; res.send(error); } else if ( existingUsernamesArray.includes(userProfile.userId) === false && (userProfile.password.length < 8 || userProfile.password.length > 20) ) { var error = "Your password is an invalid length."; res.send(error); } }); }); router.post("/api/login", function(req, res) { // User Login Authentication // ---------------------------------------------------------------------- var userProfile = req.body; console.log("userprofile" + userProfile); userInfo.all(function(response) { var existingUsernamesArray = []; var existingPasswordsArray = []; var currentUser = []; var object = { data: response }; var registerInfo = object.data; console.log({ registerInfo }); // console.log(JSON.stringify(object)); for (var i = 0; i < registerInfo.length; i++) { existingUsernamesArray.push(registerInfo[i].username); existingPasswordsArray.push(registerInfo[i].password); } console.log("existing users" + existingUsernamesArray); for (var i = 0; i < existingUsernamesArray.length; i++) { if ( userProfile.userId === existingUsernamesArray[i] && userProfile.password === existingPasswordsArray[i] ) { console.log("password match"); currentUser.push(response[i]); console.log(currentUser[0].name); var idCount = registerInfo.pop().id; idCount += 1; console.log(idCount); userInfo.update( { id: idCount }, ["name = " + "'" + currentUser[0].name + "'"], function(res) { console.log(res); } ); res.status(200).end(); } else if ( existingUsernamesArray.includes(userProfile.userId) === false ) { var error = "userId does not exist"; return res.send(error); } else if ( userProfile.userId === existingUsernamesArray[i] && userProfile.password !== existingPasswordsArray[i] ) { var error = "Incorrect password. Please try again"; return res.send(error); } } }); }); // ---------------------------------------------------------------------- // We run logic to calculate the user score and push it into the database router.post("/api/survey", function(req, res) { // we capture the user input from the html file var userInput = req.body; console.log(userInput); // This function calculates the score of the user function scoreCalculator(userInput) { var score = 0; for (let i = 0; i < userInput.data.length; i++) { score += parseInt(userInput.data[i]); } // it pushes it to the database postToDatabase(score); } // This updates the user score to the users info in the database function postToDatabase(score) { userInfo.all(function(data) { id = data.pop().id; userInfo.update({ score: score }, ["id =" + id], function(result) { console.log({ result }); if (result.affectedRows > 0) { res.json(result); } else { res.status(500).end(); } }); }); console.log({ score }); // I have to change this to an userInfo.update and then use the ID of the user that I get as a result from /api/registration } scoreCalculator(userInput); }); module.exports = router; <file_sep>// We require the orm var orm = require("../config/orm"); // We create a new object called dataOutput which we will use to read, create, update and select a single column from the database var dataOutput = { // We read files from the database all: function(cb) { orm.all("data_output", function(res) { cb(res); // console.log(res); }); }, // we read specific columns from the database selectColumn: function(col, cb) { orm.selectColumn("data_output", col, function(res) { cb(res); }); }, // we read a specific value from the database selectValue: function(col, val, cb) { orm.selectValue("data_output", col, val, function(res) { cb(res); }); }, // We insert new data into the database create: function(col, val, cb) { orm.create("data_output", col, val, function(res) { cb(res); }); }, // We update certain values in the database update: function(input, val, cb) { orm.update("data_output", input, val, function(res) { cb(res); }); } }; // create the orm file where we can render the info from the database module.exports = dataOutput; <file_sep>// We require express and initialize it var express = require("express"); var exphbs = require("express-handlebars"); var app = express(); // We create a PORT PORT = process.env.PORT || 8080; // We use middleware to use css and javascript on our html pages // The server will have its route directory in app/public/ app.use(express.static("public")); // We use a this code to parse code into json format app.use(express.urlencoded({ extended: true })); app.use(express.json()); // We use the handlebars engine as our front-end engine app.engine("handlebars", exphbs({ defaultLayout: "main" })); app.set("view engine", "handlebars"); // We require our controller var routes = require("./controller/tranquilController"); // we link the router to our express app.use(routes); app.listen(PORT, function() { console.log("Server listening at https://localhost:" + PORT); }); <file_sep>// We require the orm var orm = require("../config/orm"); // We create an object to loop through the first table in the database var userInfo = { // We use the read method to get the info from the database all: function(cb) { orm.all("user_info", function(res) { cb(res); // console.log(res); }); }, // we use selectColumn to target specific columns in the table selectColumn: function(col, cb) { orm.selectColumn("user_info", col, function(res) { cb(res); }); }, selectValue: function(col, val, cb) { orm.selectValue("user_info", col, val, function(res) { cb(res); }); }, // We use create to add data to the database create: function(col, val, cb) { orm.create("user_info", col, val, function(res) { cb(res); }); }, // We use update to set new values to certain columns in the database update: function(input, val, cb) { orm.update("user_info", input, val, function(res) { cb(res); }); } }; // We make the UserInfo object available for our controller module.exports = userInfo; <file_sep>CREATE DATABASE `qkgd01is4tbz4mr5` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; USE `qkgd01is4tbz4mr5`; CREATE TABLE user_info ( id INT AUTO_INCREMENT NOT NULL, username VARCHAR (30), password VARCHAR (45), name VARCHAR (45), score INT (10), meditationvid VARCHAR(300), exercisevid VARCHAR(300), PRIMARY KEY (id) ); CREATE TABLE data_output ( id INT AUTO_INCREMENT NOT NULL, category VARCHAR (45), min INT (10), max INT (10), meditation VARCHAR (45), exercise VARCHAR (45), description VARCHAR (300), PRIMARY KEY (id) );<file_sep>var profiles = require("../public/user-profiles"); // module.exports = function app() { // app.get("api/assessment", function(req, res) { // res.json(profiles); // }); // app.post("api/assessment", function(req, res) { // var userInput = req.body; // profiles.push(userInput); function scoreCalculator(profiles) { // We itterate through the profiles and capture for (let i = 0; i < profiles.length; i++) { var currentUser = profiles[i]; console.log({ currentUser }); var score = 0; } for (let j = 0; j < currentUser.data.length; j++) { score += currentUser.data[j]; } console.log({ score }); assessment(currentUser, score); } scoreCalculator(profiles); function assessment(userInput, score) { console.log({ userInput }); console.log(userInput.category); // create cases where we check the scores with the corresponding database tables // each case will start a function that will return a random input video in the category set in the switch case switch (userInput.category) { case "meditation": // set a function to work out a random meditation video in the stress level coming from the score meditation(score); break; case "yoga": // set a function to work out a random yoga video in the stress level coming from the score yoga(score); break; case "exercise": // set a fucntion to work out a random exercise video in the stress level coming from the score exercise(score); break; } } // this function takes the score and then function meditation(data) { console.log(data); } function yoga(data) { console.log(data); } function exercise(data) { console.log(data); } // }); // }; <file_sep>UPDATE user_info SET meditationvid = 'c1Ndym-IsQg' WHERE id = 4<file_sep># TranquiL Sometimes we just need to slow life down and take a break from this stressful world. A guided solution for stress management, Tranquil is an app that promotes anything peaceful. Users will complete an assessment to determine stress levels and will be provided with a video to correspond to helping them get to a better state of mind (i.e. yoga, mediation, and exercise). <img src="/public/assets/images/Tranquil.jpg"> To view live application: https://rugged-gunnison-25361.herokuapp.com/ 1. App allows user to register and login. 2. Upon login the User completes and submits a survey to determine their current levels of stress. 3. The User's level of stress is determined and reported on a results page. 4. The User is provided with meditation and exercise videos to assist in stress management. ## Built With * [Javascript](https://developer.mozilla.org/en-US/docs/Web/JavaScript) - The programming language used for all logic of the application. * [Materialize](https://materializecss.com/) - Used components from toolkit for developing the HTML layout. * [Handlebars](https://handlebarsjs.com/) - used for the HTML rendering of the results page. * [MYSQL](https://www.mysql.com/) - used for the database. * [CSS](https://developer.mozilla.org/en-US/docs/Web/css) - used for styling of the application. * [Adobe Fonts](https://fonts.adobe.com/) - Used to generate font styles. * [YouTube](https://developers.google.com/youtube/v3/) - Wireframe used for the video presentations. ## Authors * <NAME> - Initial work - [Github](https://github.com/Tangerinez) * <NAME> - Initial work - [Github](https://github.com/johandenver) * <NAME> - Initial work - [Github](https://github.com/lucvankerkvoort) * <NAME> - Initial work - [Github](https://github.com/kwikkid) ## Acknowledgments * Would love to give a shout out to the instructional staff at UC Berkeley Extention.
67a22d76c1fba92c86543b7a00fdb71eb63fa76b
[ "JavaScript", "SQL", "Markdown" ]
11
SQL
Tangerinez/TranquiL
313cf03bdd717572d20e6ffd45c8fc7c2636c57c
7b4f02085b4f94377b85505942a46fbd230fe343
refs/heads/master
<repo_name>vijit-m/BreakingCryptosystems<file_sep>/Subs-Perm/generate_ciphers.c #include <stdio.h> #include <string.h> #include <stdlib.h> int allperms[120][5]; int ind=0; void permute(int a[], int l, int r) { // Base case if (l == r) { for(int i=0;i<5;i++) allperms[ind][i] = a[i]; ++ind; } else { // Permutations made for (int i = l; i <= r; i++) { // Swapping done int temp = a[l]; a[l]=a[i]; a[i]=temp; // Recursion called permute(a, l+1, r); //backtrack temp = a[l]; a[l] = a[i]; a[i] = temp; } } } int main() { FILE *fptr; fptr = fopen("ciphers.txt", "w"); if (fptr == NULL) { printf("Error!"); exit(1); } //fprintf(fptr, "HI\n"); char str[] = "<KEY>"; int keylen = 5; int ikey[5] = { 1, 2, 3, 4, 5 }; permute(ikey,0,4); for(int iter=0;iter<120;iter++){ int key[5]; for(int i=0;i<5;i++)key[i]=allperms[iter][i]; for(int i=0;i<5;i++)fprintf(fptr, "%d",key[i]); fprintf(fptr, " "); int lenstr = strlen(str); char newstr[1000]; int i,j,reqlen=0,p=0; for(i=0;i<lenstr;i++) { if(((int)(str[i])>=65 && (int)(str[i])<=90) || ((int)(str[i])>=97 && (int)(str[i])<=122)) { reqlen++; newstr[p] = str[i]; p++; } } newstr[p] = '\0'; int row = (reqlen+keylen-1)/keylen; int col = keylen; char grid[row][col]; int size=0; for(i=0;i<row;i++) { for(j=0;j<col;j++) { grid[i][j] = newstr[size]; size++; } } int x=0; char decipstr[reqlen]; for(i=0;i<row;i++) { for(j=0;j<col;j++) { decipstr[x] = newstr[keylen*i + key[j] - 1]; fprintf(fptr, "%c",decipstr[x]); x++; } } fprintf(fptr, "\n"); } return 0; }<file_sep>/README.md # CS641 Course Project IITK.
a6cea2e94e6a16b382d363a7e800efe4d4398397
[ "Markdown", "C" ]
2
C
vijit-m/BreakingCryptosystems
5bb716a796e53711b39ec835b8d7c89ae02ff627
ec48800a7e32bdd7b929c0a59598abde056be9f7
refs/heads/master
<file_sep>function setup() { // Setup code goes here. // This function runs once. // The default canvas size, which is implied here, is 100 × 100 in pixels. // The 1-pixel gray border around the box is generated by style.css. } function draw() { // This function is called repeatedly. }
1577aa285bc99a0fa2e00ba533d5be9773a42714
[ "JavaScript" ]
1
JavaScript
code-warrior/p5--drawing-points
f11cc643d44a15ac7e05c40669a150834d0d5e56
2a37b20d08043d5c693bf27ddee48a03c11681df
refs/heads/master
<repo_name>JMMalm/Argus<file_sep>/Argus.Core/Enums/SortOption.cs using System; using System.Collections.Generic; using System.Text; namespace Argus.Core.Enums { public enum SortOption { Alphabetical = 0, Priority = 1 } } <file_sep>/Argus.MVC/Controllers/HomeController.cs using Argus.Core.Application; using Argus.Core.Enums; using Argus.Core.Issue; using Argus.MVC.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; namespace Argus.MVC.Controllers { public class HomeController : Controller { private readonly IConfiguration _config; private readonly IApplicationService _applicationService; private readonly IIssueService _issueService; private readonly ILogger _logger; /// <summary> /// Default constructor. /// </summary> /// <param name="config"></param> /// <param name="applicationRepo"></param> /// <param name="issueRepository"></param> /// <remarks> /// The repositories are registered as services in Startup.cs, so that's where they come from. /// </remarks> public HomeController(IConfiguration config, IApplicationService applicationService, IIssueService issueService, ILogger<HomeController> logger) { _config = config ?? throw new ArgumentNullException("Configuration cannot be null."); _applicationService = applicationService ?? throw new ArgumentNullException(nameof(applicationService), "Application Service cannot be null."); _issueService = issueService ?? throw new ArgumentNullException(nameof(issueService), "Issue Service cannot be null."); _logger = logger; } public IActionResult Index(int sortOption = 0) { IEnumerable<ApplicationModel> appsModel = null; try { SortOption sortSelection = GetValidSortOption(sortOption); // Get the Font Awesome CDN key from secrets.json. ViewBag.FontAwesomeKey = _config.GetValue<string>("fontawesome-cdn-key"); ViewBag.IssueSubmissionUrl = _config.GetValue<string>("IssueSubmissionUrl"); ViewBag.SortSelection = (int)sortSelection; // Hard-coded date because we'll only have a subset of data for a particular date. appsModel = GetApplicationIssues(new DateTime(2019, 6, 6), sortSelection); } catch (Exception ex) { _logger.LogError(ex, "Error in HomeController.Index()!"); throw; } return View(appsModel); } public IActionResult About(bool showChangeLog = false) { try { ViewBag.ShowChangeLog = showChangeLog; ViewBag.FontAwesomeKey = _config.GetValue<string>("fontawesome-cdn-key"); ViewBag.AppVersion = GetAssemblyVersion(); } catch (Exception ex) { _logger.LogError(ex, "Error in HomeController.About()!"); throw; } return View(); } public IActionResult NotFound() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { // Consider a middleware option, like so: https://code-maze.com/global-error-handling-aspnetcore/#builtinmiddleware var requestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; var feature = HttpContext.Features.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerFeature>(); // Figure out why this returns null. string requestInfo = $"{requestId}: {HttpContext.Request.QueryString}"; try { ViewBag.FontAwesomeKey = _config.GetValue<string>("fontawesome-cdn-key"); } catch (Exception ex) { _logger.LogError(ex, "Error in HomeController.About()!"); throw; } return View(new ErrorViewModel { RequestId = requestId }); } /// <summary> /// Tests writing error messages to a log file via the new middleware class. /// Temporary; will be removed later. /// </summary> /// <returns></returns> public IActionResult TestError() { throw new Exception("TEST ERROR!"); } [HttpGet] public IActionResult GetApplicationUpdates(int[] applicationIds, int sortOption = 0, bool isTest = false) { try { SortOption sortSelection = GetValidSortOption(sortOption); var applications = GetApplicationIssues(new DateTime(2019, 6, 6), sortSelection) .Where(a => applicationIds.Contains(a.Id)) .ToList(); // Modify some data to test client-side updating, because we have limited data to work with. if (isTest && applications?.Count() >= 2) { applications[0].IssueCount = 3; applications[1].IssueCount = 2; applications[2].HasUrgentPriority = !applications[2].HasUrgentPriority; } return Json(applications); } catch (Exception ex) { _logger.LogError(ex, "Error in HomeController.GetApplicationUpdates()!"); throw; } } private IEnumerable<ApplicationModel> GetApplicationIssues(DateTime date, SortOption sortSelection = SortOption.Alphabetical) { var applications = _applicationService.GetApplications()? .Where(a => a.IsEnabled == true) .OrderBy(a => a.Name); var issues = _issueService.GetIssuesByDate(date, date.AddDays(1)); List<ApplicationModel> appsModel = new List<ApplicationModel>(); foreach(var application in applications) { appsModel.Add(new ApplicationModel { Id = application.Id, Name = application.Name, IssueCount = issues.Where(i => i.ApplicationId == application.Id).Count(), HasUrgentPriority = issues.Any( i => i.ApplicationId == application.Id && i.Priority == Priority.Urgent), ProductOwnerName = application.ProductOwnerName, TeamName = application.TeamName, Url = application.Url }); } if (sortSelection == SortOption.Priority) { appsModel = ( from a in appsModel orderby a.HasUrgentPriority descending, a.IssueCount descending, a.Name select a ).ToList(); } return appsModel; } private SortOption GetValidSortOption(int sortOption) { SortOption sortSelection = (int)SortOption.Alphabetical; sortSelection = (SortOption)Enum.GetValues(typeof(SortOption)) .Cast<int>() .FirstOrDefault(o => o == sortOption); return sortSelection; } private string GetAssemblyVersion() { string appVersionAndMode = string.Format("{0} in {1} mode.", Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion, Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")?.ToUpper()); return appVersionAndMode; } } } <file_sep>/Argus.Core/Enums/Priority.cs using System; using System.Collections.Generic; using System.Text; namespace Argus.Core.Enums { public enum Priority { None = 0, Low = 1, Normal = 3, Urgent = 5 } } <file_sep>/readme.md # Argus An application monitor dashboard R&D project for my employer using .NET Core MVC and Bootstrap. Argus' main page scrolls through a listing of the company's applications and would ideally be displayed on a communal monitor (e.g. in a department or lobby). Users can then receive near-real-time status updates of applications relevant to the team and hide irrelevant applications. For my employer specifically, each application's "card" contains a link to the internal issue-reporting suite, which is only "implied" in this public version. ## Features * Responsive design for both desktop and mobile. * Ability to hide unwanted application elements from display and the option to show them again. * Includes the option to save your selection of hidden apps for future visits. * Auto-scroll functionality. * Auto-refresh functionality to fetch application updates at a pre-defined interval. (currently 60 seconds) ## Built With * ASP.NET Core MVC (.NET Core 2.2) * Bootstrap 4 * C# * Dapper 1.60.6 * jQuery 3.3.1 * Moq 4.11.0 ## Dependencies * Microsoft.AspNetCore.Mvc.Core 2.2.5 * Microsoft.Extensions.Configuration 2.2.0 * Microsoft.Extensions.Configuration.Binder 2.2.4 * Microsoft.NET.Test.Sdk 15.9.0 * MSTest.TestAdapter 1.3.2 * MSTest.TestFramework 1.3.2 ## Tools * Visual Studio 2017 * SQL Server 13.0.4001 (localdb) ## Notes * Since this is for my employer some elements of the application will be renamed or redacted entirely. * You must install the .NET Core 2.2.107 SDK to work with this application in Visual Studio 2017.<file_sep>/Argus.Tests/ApplicationServiceTests.cs using Argus.Core; using Argus.Core.Application; using Argus.Core.Data; using Argus.Infrastructure.Repositories; using Microsoft.Extensions.Configuration; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Argus.Tests { [TestClass] [TestCategory("Repository")] public class ApplicationServiceTests { private static IConfiguration _config; private static IGenericRepository<Application> _repository; private static IApplicationService _applicationService; /// <summary> /// Sets up needed objects and facilitates their re-use in tests. /// </summary> /// <param name="context"></param> [ClassInitialize] public static void Initialize(TestContext context) { _config = TestAssistant.GetConfig(); _repository = new GenericRepository<Application>(_config); _applicationService = new ApplicationService(_repository); } [TestMethod] [TestCategory("Integration")] public void GetApplications_ReturnsCollection() { var expectedCount = 1; var result = _applicationService.GetApplications(); Assert.IsInstanceOfType(result, typeof(IEnumerable<Application>)); Assert.IsTrue(result.ToList().Count >= expectedCount); } [TestMethod] [TestCategory("Unit")] public void GetApplications_Moq_ReturnsCollection() { var expectedCount = 1; Mock<IApplicationService> mockService = new Mock<IApplicationService>(); mockService .Setup(m => m.GetApplications()) .Returns(GetTestApplications()); var result = mockService.Object.GetApplications(); Assert.IsInstanceOfType(result, typeof(IEnumerable<Application>)); Assert.IsTrue(result.ToList().Count >= expectedCount); } [TestMethod] [TestCategory("Integration")] public void GetApplicationById_IdExists_ReturnsCorrectApplication() { var expectedApplicationId = 1; var result = _applicationService.GetById(expectedApplicationId); Assert.IsInstanceOfType(result, typeof(Application)); Assert.AreEqual(expectedApplicationId, result.Id); } [TestMethod] [TestCategory("Unit")] public void GetApplicationById_Moq_IdExists_ReturnsCorrectApplication() { var expectedApplicationId = 1; Application expectedApplication = GetTestApplications().ToList()[1]; Mock<IApplicationService> mockService = new Mock<IApplicationService>(); mockService .Setup(m => m.GetById(It.Is<int>(id => id == 1))) .Returns(expectedApplication); var result = mockService.Object.GetById(expectedApplicationId); Assert.IsInstanceOfType(result, typeof(Application)); Assert.AreEqual(expectedApplicationId, result.Id); } [TestMethod] [TestCategory("Unit")] public void GetApplicationById_Moq_IdDoesNotExist_ReturnsNull() { var expectedApplicationId = 1; Application expectedApplication = GetTestApplications().ToList()[1]; Mock<IApplicationService> mockService = new Mock<IApplicationService>(); mockService .Setup(m => m.GetById(It.Is<int>(id => id != 1))) .Returns(value: null); var result = mockService.Object.GetById(expectedApplicationId); Assert.IsNull(result); } private IEnumerable<Application> GetTestApplications() { return new List<Application> { new Application { Id = 0, Name = "Application_0", ProductOwnerName = "<NAME>", TeamName = "Team_1", IsEnabled = true }, new Application { Id = 1, Name = "Application_1", ProductOwnerName = "<NAME>", TeamName = "Team_2", IsEnabled = true }, new Application { Id = 1, Name = "Application_2", ProductOwnerName = "<NAME>", TeamName = "Team_3", IsEnabled = false } }; } } } <file_sep>/Argus.MVC/Middleware/ErrorLogging.cs using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Argus.MVC.Middleware { /// <summary> /// Middleware component to write exceptions to a log file. /// </summary> /// <remarks> /// This class will write to file any application errors that occur during /// the HTTP request. /// </remarks> public class ErrorLogging { private IConfiguration _config; private readonly RequestDelegate _next; /// <summary> /// Default constructor. /// </summary> /// <param name="configuration">The application configuration collection. (e.g. appSettings.json)</param> /// <param name="next">The next middleware component to execute.</param> /// <remarks> /// Call the constructor in Startup.cs' "Configure" method, like so: /// app.UseMiddleware<Middleware.ErrorLogging>(Configuration); /// /// Regarding the "next" parameter: all middleware components must either execute /// the next link in the pipeline (_next) or terminate by not calling _next. /// </remarks> public ErrorLogging(IConfiguration configuration, RequestDelegate next) { _config = configuration; _next = next; } /// <summary> /// The code that runs when this middleware is invoked. /// </summary> /// <param name="context">The HTTP request context.</param> /// <returns></returns> public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception e) { try { string logDirectory = Path.Combine(_config.GetValue<string>("logFilePath")); string requestData = FormatRequestInfo(context.Request); string exceptionData = FormatExceptionInfo(e); WriteToFile(logDirectory, $"{requestData}{Environment.NewLine}{exceptionData}"); //System.Diagnostics.Debug.WriteLine($"The following error happened: {e.Message}"); // Kept for reference. } catch (Exception logException) { // Keeping the "ex.Data" for now because it may have interesting uses later. e.Data.Add("Details", $"Logging error: {logException.Message}!"); } throw; } } /// <summary> /// Writes the provided message to the provided directory. /// </summary> /// <param name="logDirectory">The destination directory of the log file.</param> /// <param name="message">The message to be written.</param> /// <remarks> /// This method handles the creation of the actual log file if it does not exist. /// </remarks> private void WriteToFile(string logDirectory, string message) { if (!Directory.Exists(logDirectory)) { Directory.CreateDirectory(logDirectory); } string logFilePathAndName = Path.Combine($"{logDirectory}", $"{DateTime.Now.ToString("yyyy-MM-dd")}.log"); // UTC time = Central time + 5 hours. // NewLine creates a blank line between log file entries. File.AppendAllText(logFilePathAndName, $"[{DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff")}] {message}{Environment.NewLine}{Environment.NewLine}"); } /// <summary> /// Formats request data into a conveniently readable string. /// </summary> /// <param name="request">The HTTP request.</param> /// <returns>A string of the HTTP request data.</returns> private string FormatRequestInfo(HttpRequest request) { string requestData = $"Request ID: {request.HttpContext.TraceIdentifier}{Environment.NewLine}"; requestData += $"{request.Method} {request.Scheme}://{request.Host}{request.Path}{request.QueryString} ({request.HttpContext.Response.StatusCode})"; return requestData; } /// <summary> /// Formats exception data into a conveniently readable string. /// </summary> /// <param name="e"></param> /// <returns></returns> private string FormatExceptionInfo(Exception e) { string exceptionInfo = string.Empty; if (e != null) { exceptionInfo = $"{e.Message}{Environment.NewLine}{e.StackTrace}"; if (e.InnerException != null) { exceptionInfo += $"{Environment.NewLine}INNER EXCEPTION: {FormatExceptionInfo(e.InnerException)}"; } } return exceptionInfo; } } } <file_sep>/Argus.Tests/IssueServiceTests.cs using Argus.Core; using Argus.Core.Data; using Argus.Core.Issue; using Argus.Infrastructure; using Argus.Infrastructure.Repositories; using Microsoft.Extensions.Configuration; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Argus.Tests { [TestClass] [TestCategory("Repository")] public class IssueServiceTests { private static IConfiguration _config; private static IGenericRepository<Issue> _repository; private static IIssueService _issueService; /// <summary> /// Sets up needed objects and facilitates their re-use in tests. /// </summary> /// <param name="context"></param> [ClassInitialize] public static void Initialize(TestContext context) { _config = TestAssistant.GetConfig(); _repository = new GenericRepository<Issue>(_config); _issueService = new IssueService(_repository); } [TestMethod] [TestCategory("Integration")] public void GetIssues_ReturnsCollection() { var expectedCount = 1; var result = _issueService.GetIssues(); Assert.IsInstanceOfType(result, typeof(IEnumerable<Issue>)); Assert.IsTrue(result.ToList().Count >= expectedCount); } [TestMethod] [TestCategory("Integration")] public void GetIssueById_ReturnsIssue_IdsMatch() { var expectedId = 5; Issue result = _issueService.GetIssueById(expectedId); Assert.AreEqual(expectedId, result.Id); } [TestMethod] [TestCategory("Integration")] public void GetIssuesByDate_ReturnsIssues_IssuesHaveCorrectDate() { var expectedStartDate = new DateTime(2019, 06, 06); var expectedEndDate = expectedStartDate.AddDays(1); var result = _issueService.GetIssuesByDate(expectedStartDate, expectedEndDate); Assert.IsInstanceOfType(result, typeof(IEnumerable<Issue>)); result.ToList().ForEach(i => { Assert.IsTrue(expectedStartDate < i.DateSubmitted && expectedEndDate > i.DateSubmitted); }); } } } <file_sep>/Argus.Core/Application/ApplicationService.cs using Argus.Core.Data; using System; using System.Collections.Generic; using System.Text; namespace Argus.Core.Application { public class ApplicationService : IApplicationService { private readonly IGenericRepository<Application> _repo; public ApplicationService(IGenericRepository<Application> repo) { _repo = repo ?? throw new ArgumentNullException(nameof(repo), "Repository cannot be null."); } public Application GetById(int id) { return _repo.Query(SqlGetApplicationById, new { Id = id }); } public IEnumerable<Application> GetApplications() { return _repo.QueryMultiple(SqlGetApplications, null); } private readonly string SqlGetApplications = @" SELECT Id, Name, ProductOwnerName, TeamName, Url, IsEnabled, DateModified FROM Applications"; private readonly string SqlGetApplicationById = @" SELECT Id, Name, ProductOwnerName, TeamName, Url, IsEnabled, DateModified FROM Applications WHERE Id = @Id"; } } <file_sep>/Argus.ConsoleApp/Program.cs using System; using Argus.Core.Application; using Argus.Core.Data; using Argus.Infrastructure.Repositories; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Argus.ConsoleApp { public class Program { static void Main(string[] args) { var host = ConfigureHost(); /* NOTE: this is not recommended! (https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2#recommendations) * Microsoft recommends separating the console application's core logic into a separate class * to make use of the built-in dependency injection and access services that way. */ var applicationService = host.Services.GetService<IApplicationService>(); /* This is another way for configuring a console application with DI. * (https://docs.microsoft.com/en-us/dotnet/api/microsoft.extensions.commandlineutils.commandlineapplication?view=aspnetcore-1.1) * Note that the docs have not been updated for .NET Core 2.2. Some notes by <NAME>: * https://odetocode.com/blogs/scott/archive/2018/08/16/three-tips-for-console-applications-in-net-core.aspx */ //var app = new CommandLineApplication<Application>(); //app.Conventions // .UseDefaultConventions() // .UseConstructorInjection(host.Services); // app.Execute(args); var applications = applicationService.GetApplications(); foreach(var application in applications) { Console.WriteLine(application.Name); } Console.WriteLine($"{Environment.NewLine}Press any key to continue."); Console.Beep(); Console.ReadKey(); } /// <summary> /// Sets up the host and configures its services, logging, etc., for dependency injection. /// </summary> /// <returns></returns> private static IHost ConfigureHost() { var host = new HostBuilder() .ConfigureAppConfiguration((hostingContext, config) => { config //.SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appSettings.json", optional: false, reloadOnChange: true) .Build(); }) .ConfigureServices((hostContext, services) => { services.Configure<HostOptions>(option => { option.ShutdownTimeout = TimeSpan.FromSeconds(20); }); services.AddLogging(loggingBuilder => { loggingBuilder.AddConfiguration(hostContext.Configuration.GetSection("Logging")); loggingBuilder.AddConsole(); //loggingBuilder.AddConsole(options => //{ // options.IncludeScopes = true; //}); }); services.AddScoped<IGenericRepository<Application>, GenericRepository<Application>>(); services.AddScoped<IApplicationService, ApplicationService>(); }) .Build(); return host; } } } <file_sep>/Argus.Tests/TestData.cs using Argus.Core.Application; using Argus.Core.Enums; using Argus.Core.Issue; using Moq; using System; using System.Collections.Generic; using System.Text; namespace Argus.Tests { public static class TestData { public static Mock<IApplicationService> GetMockApplicationService() { Mock<IApplicationService> mockApplicationService = new Mock<IApplicationService>(); mockApplicationService .Setup(m => m.GetApplications()) .Returns(new List<Application> { new Application { Id = 1, Name = "Application_1", Url = "www.Application_1.com", IsEnabled = true }, new Application { Id = 2, Name = "Application_2", Url = "www.Application_2.com", IsEnabled = false }, new Application { Id = 3, Name = "Application_3", Url = "www.Application_3.com", IsEnabled = true } }); return mockApplicationService; } public static Mock<IIssueService> GetMockIssueService(DateTime date) { Mock<IIssueService> mockIssueService = new Mock<IIssueService>(); mockIssueService .Setup(m => m.GetIssuesByDate(date, date.AddDays(1))) .Returns(new List<Issue> { new Issue { Id = 1, ApplicationId = 1, DateSubmitted = date, Priority = Priority.Normal }, new Issue { Id = 2, ApplicationId = 2, DateSubmitted = date, Priority = Priority.Normal }, new Issue { Id = 3, ApplicationId = 3, DateSubmitted = date, Priority = Priority.Urgent } }); return mockIssueService; } } } <file_sep>/Argus.Core/Issue/IIssueService.cs using System; using System.Collections.Generic; using System.Text; namespace Argus.Core.Issue { public interface IIssueService { IEnumerable<Issue> GetIssues(); IEnumerable<Issue> GetIssuesByDate(DateTime date, DateTime endDate); Issue GetIssueById(int id); } } <file_sep>/Argus.MVC/ViewComponents/ChangeLogViewComponent.cs using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace Argus.MVC.ViewComponents { public class ChangeLogViewComponent : ViewComponent { public ChangeLogViewComponent() { } public async Task<IViewComponentResult> InvokeAsync() { string changeLogContent = string.Empty; string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/content/changelog.html"); using (var reader = File.OpenText(filePath)) { changeLogContent = await reader.ReadToEndAsync(); } return View("Default", changeLogContent); } } } <file_sep>/Argus.MVC/Program.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace Argus.MVC { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appSettings.json", optional: false, reloadOnChange: true) .AddJsonFile("secrets.json", optional: false, reloadOnChange: true) .Build(); }) .ConfigureLogging((hostingContext, logging) => { logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.ClearProviders(); logging.AddConsole(); // logging.AddConsole(options => options.IncludeScopes = true); // Allows use of "using" blocks (https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?tabs=aspnetcore2x&view=aspnetcore-2.2#log-scopes) logging.AddEventLog(); // Logs to the Windows Event log. (https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?tabs=aspnetcore2x&view=aspnetcore-2.2#windows-eventlog-provider) }) .UseStartup<Startup>(); } } <file_sep>/Argus.Tests/TestAssistant.cs using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Argus.Tests { /// <summary> /// Handles common logic and figurative tasks for tests to reduce duplicate code. /// </summary> public class TestAssistant { public static IConfiguration GetConfig() { return new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appSettings.json", optional: false, reloadOnChange: true) .AddJsonFile(@"c:\code\argus\argus.MVC\secrets.json", optional: false, reloadOnChange: true) .Build(); } } } <file_sep>/Argus.Core/Issue/IssueService.cs using Argus.Core.Data; using System; using System.Collections.Generic; using System.Text; namespace Argus.Core.Issue { public class IssueService : IIssueService { private readonly IGenericRepository<Issue> _repo; public IssueService(IGenericRepository<Issue> repo) { _repo = repo ?? throw new ArgumentNullException(nameof(repo), "Repository cannot be null."); } public Issue GetIssueById(int id) { return _repo.Query(SqlGetIssueById, new { Id = id }); } public IEnumerable<Issue> GetIssues() { return _repo.QueryMultiple(SqlGetIssues, null); } public IEnumerable<Issue> GetIssuesByDate(DateTime date, DateTime endDate) { return _repo.QueryMultiple(SqlGetIssuesByDate, new { Date = date, EndDate = endDate }); } private readonly string SqlGetIssues = @" SELECT Id, ApplicationId, Description, UserName, DateSubmitted, DateClosed, Priority FROM Issues"; private readonly string SqlGetIssueById = @" SELECT Id, ApplicationId, Description, UserName, DateSubmitted, DateClosed, Priority FROM Issues WHERE Id = @Id"; private readonly string SqlGetIssuesByDate = @" SELECT Id, ApplicationId, Description, UserName, DateSubmitted, DateClosed, Priority FROM Issues WHERE DateSubmitted >= @Date AND DateSubmitted < @EndDate"; } } <file_sep>/Argus.Core/Data/IGenericRepository.cs using System; using System.Collections.Generic; using System.Text; namespace Argus.Core.Data { public interface IGenericRepository<TEntity> where TEntity : class, IEntity { TEntity Query(string sqlOrProcedure, object arguments); IEnumerable<TEntity> QueryMultiple(string sqlOrProcedure, object arguments); } } <file_sep>/Argus.MVC/wwwroot/js/site.js var refreshInterval = null; var scrollInterval = null; var sortOption = "0"; $(document).ready(function () { if (isAfterHours()) { $('#AfterHoursAlert').fadeIn(); } else { $('#AfterHoursAlert').fadeOut(); } sortOption = $('#SortSelectionInputGroup').val(); $('#settingsLink').click(function () { $('#settingsModal').modal('show'); }) $("#settingsModal").on("hidden.bs.modal", function () { var selectedSortOption = $('#SortSelectionInputGroup').val(); if (sortOption !== selectedSortOption) { document.location.href = location.origin + '?sortOption=' + selectedSortOption; } }); $('#AutoScrollCheckbox').change(function () { if ($('#AutoScrollCheckbox').prop('checked')) { scrollInterval = setInterval(autoScroll, 2000); } else { clearInterval(scrollInterval); } }) $('#AutoRefreshCheckbox').change(function () { if ($('#AutoRefreshCheckbox').prop('checked')) { refreshInterval = setInterval(getApplicationUpdates, 120000); // 120 seconds } else { clearInterval(refreshInterval); } }) $('#UnhideCheckbox').change(function () { if ($('#UnhideCheckbox').prop('checked')) { $('div.col-sm-4[data-hidden="true"]') .attr('data-hidden', false) .fadeIn(); } else { $('div.col-sm-4[data-hidden="false"]') .attr('data-hidden', true) .fadeOut(); } }); $('h5 > i').click(function () { $(this).parents('div.col-sm-4').attr('data-hidden', true).fadeOut(); $('#UnhideCheckbox').prop('checked', false) }); checkSavedSettings(); }) function autoScroll() { // Time to scroll to bottom $('html, body').animate({ scrollTop: 0 }, 2000); // Scroll to top setTimeout(function () { $('html, body').animate({ scrollTop: $(document).height() }, 16000); }, 2000); //call every 2000 miliseconds } function getApplicationUpdates(isTest = false) { if (isAfterHours() && !isTest) { $('#AfterHoursAlert').fadeIn(); console.log('After hours detected - skipping update request.') return; } else { $('#AfterHoursAlert').fadeOut(); } $('#loadingModal').modal('show'); var ids = getIdArray('div.col-sm-4:not([data-hidden="true"'); var sortOption = $('#SortSelectionInputGroup').val(); $.ajax({ type: 'GET', contentType: 'application/json', data: { 'applicationIds': ids, 'sortOption': sortOption, 'isTest': isTest }, dataType: "json", traditional: true, url: '/Home/GetApplicationUpdates', success: function (data) { $.each(data, function (index, data) { updateApplication(data); }); }, error: function (xhr, error) { console.error(xhr.status + ': There was a problem on the server.'); }, complete: function () { $('#StatusDateTime').text(new Date($.now()).toLocaleString()); setTimeout(function () { $('#loadingModal').modal('hide'); }, 1000); } }); } function updateApplication(application) { if (!application) { console.warn('Null application passed for update.'); }; var cardColor = 'bg-success'; var cardTextColor = 'text-white'; var $applicationCard = $('div.col-sm-4[data-id=' + application.id + ']'); $applicationCard.find('button > span').text(application.issueCount); if (application.hasUrgentPriority || application.issueCount >= 3) { cardColor = 'bg-danger'; } else if (!application.hasUrgentPriority && application.issueCount != 0) { cardColor = 'bg-warning'; cardTextColor = 'text-dark'; } $applicationCard .find("[class*='bg-']") .fadeIn() .removeClass('bg-success bg-warning bg-danger text-light text-dark') .addClass('' + cardColor + ' ' + cardTextColor + ''); if (application.hasUrgentPriority && !$applicationCard.find('i.pulse').length) { $applicationCard .find('i') .before('<i class="fa fa-exclamation-triangle pulse" aria-hidden="true" title="High priority issue(s) have been reported."></i>'); } else if (!application.hasUrgentPriority && $applicationCard.find('i.pulse').length) { $applicationCard.find('i.pulse').remove(); } } function showReportIssueModal() { $('#reportIssueModal').modal('show'); } function isAfterHours() { var localHour = new Date($.now()).getHours(); return (localHour >= 18 || localHour < 8); } function saveSettings() { var hiddenIds = getIdArray('div.col-sm-4[data-hidden]'); localStorage.setItem('hiddenApps', hiddenIds); localStorage.setItem('showHidden', $('#UnhideCheckbox').prop('checked')); localStorage.setItem('sortOption', $('#SortSelectionInputGroup').val()); localStorage.setItem('saveSettings', true); localStorage.setItem('enabledAutoRefresh', $('#AutoRefreshCheckbox').prop('checked')); localStorage.setItem('enabledAutoScroll', $('#AutoScrollCheckbox').prop('checked')); $('#SaveSettingsAlert').fadeIn(); setTimeout(function () { $("#SaveSettingsAlert").fadeOut(2000); }, 5000); } function checkSavedSettings() { if (localStorage.getItem('saveSettings')) { var hiddenIds = localStorage.getItem('hiddenApps'); var showHidden = (localStorage.getItem('showHidden') == 'true'); if (hiddenIds) { hiddenIds.split(',').forEach(function (v) { $('div.col-sm-4[data-id="' + v + '"]') .attr('data-hidden', showHidden); }); $('#UnhideCheckbox') .prop('checked', showHidden) .change(); } if (localStorage.getItem('enabledAutoRefresh') == 'true') { $('#AutoRefreshCheckbox') .prop('checked', true) .change(); } if (localStorage.getItem('enabledAutoScroll') == 'true') { $('#AutoScrollCheckbox') .prop('checked', true) .change(); } } } function resetSettings() { localStorage.removeItem('enabledAutoRefresh'); $('#AutoRefreshCheckbox') .prop('checked', false) .change(); localStorage.removeItem('enabledAutoScroll'); $('#AutoScrollCheckbox') .prop('checked', false) .change(); localStorage.removeItem('hiddenApps'); localStorage.removeItem('showHidden'); $('div.col-sm-4[data-hidden]') .removeAttr('data-hidden') .fadeIn(); $('#UnhideCheckbox') .prop('checked', false); localStorage.removeItem('sortOption'); $('#SortSelectionInputGroup').val(0); localStorage.removeItem('saveSettings'); $('#ResetSettingsAlert').fadeIn(); setTimeout(function () { $("#ResetSettingsAlert").fadeOut(2000); }, 5000); } function checkSortOption() { var sortOption = localStorage.getItem('sortOption'); if (sortOption && window.location.href.indexOf("sortOption") == -1) { window.location.href = location.origin + '?sortOption=' + sortOption; } } function getIdArray(selector) { var ids = []; $(selector).each(function () { var id = $(this).attr('data-id'); if (id) { ids.push(id); } }); return ids; }<file_sep>/Argus.MVC/Models/ApplicationModel.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Argus.MVC.Models { /// <summary> /// An aggregation of a company application and issue data /// for the reporting dashboard. /// </summary> public class ApplicationModel { public int Id { get; set; } public string Name { get; set; } public int IssueCount { get; set; } public bool HasUrgentPriority { get; set; } public string ProductOwnerName { get; set; } public string TeamName { get; set; } public string Url { get; set; } } } <file_sep>/Argus.Tests/HomeControllerTests.cs using Argus.Core.Application; using Argus.Core.Enums; using Argus.Core.Issue; using Argus.Infrastructure.Repositories; using Argus.MVC.Controllers; using Argus.MVC.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Collections.Generic; using System.Linq; namespace Argus.Tests { [TestClass] [TestCategory("Controller")] public class HomeControllerTests { private static IConfiguration _config; private static IApplicationService _applicationService; private static IIssueService _issueService; private static Mock<ILogger<HomeController>> _logger; /// <summary> /// Sets up needed objects and facilitates their re-use in tests. /// </summary> /// <param name="context"></param> [ClassInitialize] public static void Initialize(TestContext context) { _config = TestAssistant.GetConfig(); _applicationService = new ApplicationService(new GenericRepository<Application>(_config)); _issueService = new IssueService(new GenericRepository<Issue>(_config)); _logger = new Mock<ILogger<HomeController>>(); } [TestMethod] [TestCategory("Integration")] public void Index_SortOptionDefault_ModelIsNotNull() { int expectedMinimumModelCount = 1; var controller = new HomeController(_config, _applicationService, _issueService, _logger.Object); var result = controller.Index() as ViewResult; var resultModel = (result as ViewResult).Model as IEnumerable<ApplicationModel>; Assert.IsNotNull(result.Model); Assert.IsFalse(string.IsNullOrWhiteSpace(controller.ViewBag.FontAwesomeKey)); Assert.IsTrue(resultModel.Count() >= expectedMinimumModelCount); } [TestMethod] [TestCategory("Integration")] public void Index_SortOptionPriority_ModelIsInPriorityOrder() { int expectedMinimumModelCount = 1; var controller = new HomeController(_config, _applicationService, _issueService, _logger.Object); var result = controller.Index(1) as ViewResult; var resultModel = (result as ViewResult).Model as IEnumerable<ApplicationModel>; Assert.IsNotNull(result.Model); Assert.IsFalse(string.IsNullOrWhiteSpace(controller.ViewBag.FontAwesomeKey)); Assert.IsTrue(resultModel.Count() >= expectedMinimumModelCount); Assert.IsTrue(resultModel.First().HasUrgentPriority); } [TestMethod] [TestCategory("Integration")] public void About_FontAwesomeKeyIsFound_ReturnsView() { var controller = new HomeController(_config, _applicationService, _issueService, _logger.Object); var result = controller.About() as ViewResult; Assert.IsTrue(!string.IsNullOrWhiteSpace(result.ViewData["FontAwesomeKey"].ToString())); } [TestMethod] [TestCategory("Integration")] public void GetApplicationUpdates_SortOptionDefault_SpecificIdsReturned() { int[] ids = new int[] { 1, 2, 4}; var controller = new HomeController(_config, _applicationService, _issueService, _logger.Object); var result = (JsonResult)controller.GetApplicationUpdates(ids); var applications = result.Value as List<ApplicationModel>; Assert.AreEqual(ids.Length, applications.Count); applications.ForEach(a => { Assert.IsTrue(ids.Contains(a.Id)); }); } [TestMethod] [TestCategory("Integration")] public void GetApplicationUpdates_SortOptionPriority_ResultIsInPriorityOrder() { int[] ids = new int[] { 1, 2, 6 }; var controller = new HomeController(_config, _applicationService, _issueService, _logger.Object); var result = (JsonResult)controller.GetApplicationUpdates(ids, (int)SortOption.Priority); var applications = result.Value as List<ApplicationModel>; Assert.AreEqual(ids.Length, applications.Count); applications.ForEach(a => { Assert.IsTrue(ids.Contains(a.Id)); }); Assert.IsTrue(applications.First().HasUrgentPriority); } [TestMethod] [TestCategory("Unit")] public void Index_Moq_ModelExcludedDisabledApps_ModelHasUrgentPriorityIssue() { DateTime date = new DateTime(2019, 6, 6); int expectedModelCount = 2; int expectedUrgentPriorityCount = 1; Mock<IApplicationService> mockApplicationService = TestData.GetMockApplicationService(); Mock<IIssueService> mockIssueService = TestData.GetMockIssueService(date); HomeController mockController = new HomeController(_config, mockApplicationService.Object, mockIssueService.Object, _logger.Object); var result = mockController.Index() as ViewResult; var resultModel = (result as ViewResult).Model as IEnumerable<ApplicationModel>; mockApplicationService.Verify(a => a.GetApplications(), Times.Once); mockIssueService.Verify(i => i.GetIssuesByDate(It.IsAny<DateTime>(), It.IsAny<DateTime>()), Times.Once); Assert.IsNotNull(result); Assert.IsFalse(string.IsNullOrWhiteSpace(mockController.ViewBag.FontAwesomeKey)); // Ensure only enabled apps are displayed: Assert.AreEqual(resultModel.Count(), expectedModelCount); // Ensure Index properly vetted Urgent priority issue. Assert.AreEqual(resultModel.Where(a => a.HasUrgentPriority).Count(), expectedUrgentPriorityCount); } } } <file_sep>/Argus.Core/Application/Application.cs using Argus.Core.Data; using System; using System.Collections.Generic; using System.Text; namespace Argus.Core.Application { public class Application : IEntity { public int Id { get; set; } public string Name { get; set; } public string ProductOwnerName { get; set; } public string TeamName { get; set; } public string Url { get; set; } /// <summary> /// Determines if the application is set to display in the UI. /// </summary> public bool IsEnabled { get; set; } public DateTime DateModified { get; set; } } } <file_sep>/Argus.Infrastructure/Repositories/GenericRepository.cs using System; using System.Collections.Generic; using System.Text; using Dapper; using System.Data; using System.Data.SqlClient; using Microsoft.Extensions.Configuration; using Argus.Core.Data; namespace Argus.Infrastructure.Repositories { public class GenericRepository<TEntity> : IGenericRepository<TEntity>, IDisposable where TEntity : class, IEntity { // See more here: // https://codereview.stackexchange.com/questions/177588/generic-repository-without-entity-framework // private readonly IConfiguration _config; private readonly string _connectionString; private IDbConnection _connection; public GenericRepository(IConfiguration config) { _config = config ?? throw new ArgumentNullException(nameof(config), "Configuration cannot be null."); _connectionString = _config.GetConnectionString("Argus") ?? throw new ArgumentNullException("Connection string cannot be null."); //_connection = new SqlConnection(_config.GetConnectionString(connectionString)); } public void Dispose() { if (_connection != null) { _connection.Dispose(); } } public TEntity Query(string sqlOrProcedure, object arguments) { TEntity result = default(TEntity); TryExecute<TEntity>(() => result = _connection.QuerySingle<TEntity>(sqlOrProcedure, arguments, commandType: CommandType.Text, commandTimeout: 60)); return result; } public IEnumerable<TEntity> QueryMultiple(string sqlOrProcedure, object arguments) { IEnumerable<TEntity> result = default(IEnumerable<TEntity>); TryExecute<TEntity>(() => result = _connection.Query<TEntity>(sqlOrProcedure, arguments, commandType: CommandType.Text, commandTimeout: 60)); return result; } private void TryExecute<IEntity>(Action action) { try { using (_connection = new SqlConnection(_connectionString)) { action(); } } catch (SqlException sx) { throw new Exception($"{DateTime.Now}: SQL error {sx.ErrorCode}: {sx.Message}", sx); } catch (Exception ex) { throw new Exception($"{DateTime.Now}: Dapper error: {ex.Message}", ex); } } } } <file_sep>/Argus.Core/Issue/Issue.cs using Argus.Core.Data; using Argus.Core.Enums; using System; using System.Collections.Generic; using System.Text; namespace Argus.Core.Issue { public class Issue : IEntity { public int Id { get; set; } public int ApplicationId { get; set; } public string Description { get; set; } public string UserName { get; set; } public DateTime DateModified { get; set; } public DateTime DateSubmitted { get; set; } public DateTime DateClosed { get; set; } public Priority Priority { get; set; } } } <file_sep>/Argus.Core/Application/IApplicationService.cs using System; using System.Collections.Generic; using System.Text; namespace Argus.Core.Application { public interface IApplicationService { Application GetById(int id); IEnumerable<Application> GetApplications(); } }
b2176505c4c3d83f41185a62c3e81882c2943003
[ "Markdown", "C#", "JavaScript" ]
23
C#
JMMalm/Argus
2eb0160d8eef1658de4203c59304038bfbdbf225
253afd74f664f2118aa6c6d81bf97129487f90f3
refs/heads/master
<file_sep>#include <cstdio> #include <cstdlib> #include <mkl.h> int min(int argc, char*argv[]){ double fin, inicio = dsecnd(); inicio = dsecnd(); printf("Hola, weqeq"); fin = dsecnd(); prinf("Tiempo: %lf usec\n", (fin - inicio)*1.0e6); std::getchar(); return 0; }<file_sep>#include <cstdio> #include <cstdlib> #include <mkl.h> int main(int argc, char*argv[]){ double fin, inicio = dsecnd(); inicio = dsecnd(); /* BODY */ double A[9] = {1.0, 2.0, 3.0, 4.0, 5, 6, 7, 8, 9}; double B[3] = { 10.0, 11.0, 12.0 }; double C[3]; // calculo de la norma o modulo cblas_dgemv(CblasRowMajor,CblasNoTrans,3,3,1.0,A,3,B,1,0.0,C,1); // RowMajor dice que se codifica por filas, CblasNoTrans no es transpose for (int i = 0; i < 3; i++) printf("%lf\n", C[i]); fin = dsecnd(); printf("Tiempo: %lf msec\n\n",(fin-inicio)*1.0e3); cblas_dgemv(CblasRowMajor, CblasTrans, 3, 3, 1.0, A, 3, B, 1, 0.0, C, 1); // RowMajor dice que se codifica por filas, CblasNoTrans no es transpose for (int i = 0; i < 3; i++) printf("%lf\n", C[i]); fin = dsecnd(); printf("Tiempo: %lf msec\n\n", (fin - inicio)*1.0e3); std::getchar(); return 0; }<file_sep>#include <cstdio> #include <cstdlib> #include <mkl.h> int main(int argc, char*argv[]){ double fin, inicio = dsecnd(); inicio = dsecnd(); /* BODY */ double A[4] = { 1.0, 2.0, 3.0, 4.0 }; double B[4] = { 5.0, 6.0, 7.0, 8.0 }; // calculo de la norma o modulo double norma = cblas_dnrm2(4, A, 1); // ese 1 es el incremento printf("Norma de A: %lf\n", norma); norma = cblas_dnrm2(4, B, 1); printf("Norma de B: %lf\n", norma); // calculo de p escalar double pescalar = cblas_ddot(4, A, 1, B, 1); cblas_daxpy(4, 2.0, A, 1, B, 1); printf("Suma ponderada:\n"); for (int i = 0; i < 4; i++) printf("%lf\n", B[i]); fin = dsecnd(); std::getchar(); return 0; }
a256b8f4984244360edc9c429642c2dc20359238
[ "C++" ]
3
C++
hectorgarbisu/MNC-Practica3
1bf2c5c3e73726c1baedf0b8d4f7af0b3ceb1654
69f9274e9d4cb337225cc6de85cbc72422dd5450
refs/heads/master
<repo_name>woodenphone/Derpibooru-dl<file_sep>/find_duplicates.py #------------------------------------------------------------------------------- # Name: move duplicates # Purpose: # # Author: new # # Created: 27/06/2014 # Copyright: (c) new 2014 # Licence: <your licence> #------------------------------------------------------------------------------- #!/usr/bin/env python import hashlib import logging import os import shutil import derpibooru_dl def setup_logging(log_file_path): # Setup logging (Before running any other code) # http://inventwithpython.com/blog/2012/04/06/stop-using-print-for-debugging-a-5-minute-quickstart-guide-to-pythons-logging-module/ assert( len(log_file_path) > 1 ) assert( type(log_file_path) == type("") ) global logger log_file_folder = os.path.split(log_file_path)[0] if not os.path.exists(log_file_folder): os.makedirs(log_file_folder) logger = logging.getLogger() logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') fh = logging.FileHandler(log_file_path) fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) logger.addHandler(fh) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) logger.addHandler(ch) logging.debug('Logging started.') return def uniquify(seq, idfun=None): # List uniquifier from # http://www.peterbe.com/plog/uniqifiers-benchmark # order preserving if idfun is None: def idfun(x): return x seen = {} result = [] for item in seq: marker = idfun(item) # in old Python versions: # if seen.has_key(marker) # but in new ones: if marker in seen: continue seen[marker] = 1 result.append(item) return result def walk_for_file_paths(start_path): """Use os.walk to collect a list of paths to files mathcing input parameters. Takes in a starting path and a list of patterns to check against filenames Patterns follow fnmatch conventions.""" logging.debug("Starting walk. start_path:" + start_path) assert(type(start_path) == type("")) matches = [] for root, dirs, files in os.walk(start_path): dirs[:] = [d for d in dirs if d not in ['json']]# Scanning /json/ is far too slow for large folders, skip it. c = 1 logging.debug("root: "+root) for filename in files: c += 1 if (c % 1000) == 0: logging.debug("File # "+str(c)+": "+filename) match = os.path.join(root,filename) matches.append(match) logging.debug("end folder") logging.debug("Finished walk.") return matches def hash_file(file_path): """Generate a SHA512 hash for a file""" # http://www.pythoncentral.io/hashing-files-with-python/ BLOCKSIZE = 65536 hasher = hashlib.sha512() with open(file_path, 'rb') as afile: buf = afile.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = afile.read(BLOCKSIZE) file_hash = u"" + hasher.hexdigest()# convert to unicode return file_hash def find_duplicates(input_folder): """Find duplicates in a folder""" logging.info("Looking for duplicates in "+input_folder) file_paths = walk_for_file_paths(input_folder) hash_dict = {} # {hash : file_path} hash_matches = [] logging.info("Generating and compating hashes") c = 0 for file_path in file_paths: c += 1 if (c % 1000) == 0: logging.debug("Hashing file #"+str(c)+": "+file_path) file_hash = hash_file(file_path) # Check if hash has been seen try: previously_seen = hash_dict[file_hash] logging.info("Match! "+hash_dict[file_hash]+" has the same hash as "+file_path) # Add both to move list hash_matches.append(hash_dict[file_hash])# From hash dict hash_matches.append(file_path)# Current except KeyError, ke: # If no match in dict hash_dict[file_hash] = file_path # Uniquify move list files_to_move = uniquify(hash_matches) return files_to_move def move_duplicates(input_folder,output_folder,pickle_path,no_move=False): """Find and move all duplicate files in a folder""" duplicates_to_move = find_duplicates(input_folder) logging.info("Found "+str(len(duplicates_to_move))+" items with hashes matching another file") logging.debug("Duplicates found: "+str(duplicates_to_move)) derpibooru_dl.save_pickle(pickle_path, duplicates_to_move) logging.info("Done moving duplicates") return def move_from_pickle(pickle_path,output_folder,no_move=False): logging.info("Moving files from pickle: "+pickle_path) file_paths = derpibooru_dl.read_pickle(pickle_path) move_files(file_paths,output_folder,no_move=False) return def move_files(file_paths,output_folder,no_move=False): logging.info("Moving files...") for file_path in file_paths: move_file(file_path, output_folder, no_move) logging.info("Finished moving files.") return def move_file(from_path,output_folder,no_move=False): """Move a file to a specified folder or copy it if no_move is True""" # Figure out the filename filename = os.path.basename(from_path) # Make the output path output_path = os.path.join(output_folder, filename) try: # Ensure folder exists if not os.path.exists(output_folder): os.makedirs(output_folder) if no_move is True: logging.info("Copying "+from_path+" to "+output_path) # Copy file shutil.copy2(from_path, output_path) return elif no_move is False: logging.info("Moving "+from_path+" to "+output_path) # Move file shutil.move(from_path, output_path) return else: raise ValueError except IOError, err: logging.error("Error copying/moving files!") logging.debug( repr( locals() ) ) logging.exception(err) return def main(): input_folder = "h:\\derpibooru_dl\\download\\combined_downloads" output_folder = "duplicates" global pickle_path pickle_path = os.path.join("debug","found_duplicates.pickle") move_from_pickle(pickle_path, output_folder, no_move=False) return move_duplicates(input_folder, output_folder, pickle_path, no_move = True) if __name__ == '__main__': # Setup logging setup_logging(os.path.join("debug","derpibooru_move_duplicate_files_log.txt")) try: #cj = cookielib.LWPCookieJar() #setup_browser() main() except Exception, err: # Log exceptions logging.critical("Unhandled exception!") logging.critical(str( type(err) ) ) logging.exception(err) logging.info( "Program finished.") #raw_input("Press return to close") <file_sep>/sort_dl_list.py #------------------------------------------------------------------------------- # Name: For sorting download lists # Purpose: # # Author: new # # Created: 24/03/2014 # Copyright: (c) new 2014 # Licence: <your licence> #------------------------------------------------------------------------------- #!/usr/bin/env python import derpibooru_dl def artists_at_top(query_list): """Put anything with the string "artist" at the top of the list""" put_at_top = [] put_at_bottom = [] for query in query_list: if "artist".lower() in query.lower(): put_at_top.append(query) else: put_at_bottom.append(query) output_list = put_at_top + put_at_bottom return output_list def main(): input_list_path = "config\\to_sort.txt" output_list_path = "config\\artists_at_top.txt" input_list = derpibooru_dl.import_list(input_list_path) artists_at_top_list = artists_at_top(input_list) derpibooru_dl.append_list(artists_at_top_list, output_list_path, initial_text="# Artists at the top.\n",overwrite=True) if __name__ == '__main__': main() <file_sep>/README.md # Derpibooru Downloader ## Instalation and configuration There are two ways to run Derpibooru_dl, from a windows executable or directly from the script itself. ### Standalone executable version for Windows - Suggested for anyone without programming experience. - This only contains the downloader itself. - Download the latest version (In green at the top) from https://github.com/woodenphone/Derpibooru-dl/releases - Extract the contents of the .zip into a folder. - Read the configuration section for the next steps. ### Python scripts - This is only suggested for those with experience in using python. - You need to have Python version **2.6 or 2.7** installed first. [You can download it here. ](https://www.python.org/download/) - Then you need pip installed. [See here for the docs](http://pip.readthedocs.org/en/latest/installing.html). - Then in your command line, do `pip install mechanize derpybooru`. - Read the configuration section for the next steps. ### Configuration and running for all versions - We need to run derpibooru_dl to create settings files. - On Windows, using the standalone executable version, run `derpibooru_dl.exe`. - On Windows, macOS and GNU/Linux, run `python derpibooru_dl.py` in a command line terminal. - Without a valid API key you will not be able to download anything not visible in the default guest view. - Copy your API key from [https://derpibooru.org/users/edit](https://derpibooru.org/users/edit) - Past it to the appropriate line in the `derpibooru_dl_config.cfg` inside the `config` folder. (e.g. `api_key = Ap1k3Yh3Re`) - Put the queries you want to download in `derpibooru_dl_tag_list.txt` in the `config` folder, with one query per line. - Full derpibooru search syntax MAY be available. Syntax guide is available at [https://derpibooru.org/search/syntax](https://derpibooru.org/search/syntax) - If your query works on the site but not in this script, please send a private message to my account "misspelledletter" on derpibooru. - Example of query list. ```` Tag1 tag_2 tag+3 T4g 4 tag-five || tag-six ```` - Run derpibooru_dl again to download your set. - After a tag has been processed, it will be written to the file `derpibooru_done_list.txt`, in the `config` folder. - Derpibooru-dl will close itself after it has finished. ### Explaination of settings: For boolean (yes or no) settings, use these: `True` or `False` (case sensitive!) ````ini [Login] api_key = **Key used to access API (You will need to fill this in.)** [Download] reverse = **Work backwards** output_folder = **path to output to** download_submission_ids_list = **Should submission IDs form the input list be downloaded** download_query_list = **Should queries from the input list be downloaded** output_long_filenames = **Should the derpibooru filenames be used? (UNSUPPORTED! USE AT OWN RISK!)** input_list_path = **Path to a text file containing queries, ids, etc** done_list_path = **Path to record finished tasks** failed_list_path = **Path to record failed tasks** save_to_query_folder = **Should each query/tag/etc save to a folder of QUERY_NAME or use one single folder for everything** skip_downloads = **Should no downloads be attempted** sequentially_download_everything = **Should the range download mode try to save every possible submission?** go_backwards_when_using_sequentially_download_everything = **Start at the most recent submission instead of the oldest when trying to download everything.** download_last_week = **Should the last 7000 submissions be downloaded (Approx 1 weeks worth)** skip_glob_duplicate_check = **You should probably not use this unless you know what you are doing. (Speedhack for use with single output folder)** move_on_fail_verification = **Should files that fail the verification be moved? If false they will only be copied.** save_comments = **Should image comments be requested and saved, uses more resources on both client and server.** [General] show_menu **Should a text based menu be shown instead of automatically running the batch mode?** hold_window_open = **Should the window be kept open after all tasks are done, to allow the user to confirm the program worked** ```` ### Example of typical settings - This configuration should be fine for most users - Make sure to use your own API key, the one here is just an example ````ini [Login] api_key = Replace_this_with_your_API_key [Download] reverse = False output_folder = download download_submission_ids_list = True download_query_list = True output_long_filenames = False input_list_path = config\derpibooru_dl_tag_list.txt done_list_path = config\derpibooru_done_list.txt failed_list_path = config\derpibooru_failed_list.txt save_to_query_folder = True skip_downloads = False sequentially_download_everything = False go_backwards_when_using_sequentially_download_everything = False download_last_week = False skip_glob_duplicate_check = False skip_known_deleted = True deleted_submissions_list_path = config\deleted_submissions.txt move_on_fail_verification = False save_comments = False [General] show_menu = True hold_window_open = True ```` ### Tips and Fixes - When editing settings or input lists, you may find that your text editor does not display items on different lines properly. - This is probably due to the text editor you are using, try using a different editor, such as notepad++ - Known incompatible editors: ```` Microsoft Notepad (Ships with Windows) ```` - Known compatible editors: ```` Notepad++ [http://www.notepad-plus-plus.org/](http://www.notepad-plus-plus.org/) ```` - ~~I've written a guide with screenshots for the windows .exe releases. [Guide link](http://evil-vortex.com/Guide_2014-10-28.pdf)~~ <file_sep>/derpibooru_dl.py #------------------------------------------------------------------------------- # Name: Derpibooru-dl # Purpose: # # Author: woodenphone # # Created: 2014-02-88 # Copyright: (c) new 2014 # Licence: <your licence> #------------------------------------------------------------------------------- #!/usr/bin/env python import time import os import sys import re import mechanize import cookielib import logging import urllib2 import httplib import random import glob import ConfigParser import HTMLParser import json import shutil import pickle import socket import hashlib import string import argparse import derpibooru # getwithinfo() GET_REQUEST_DELAY = 0 GET_RETRY_DELAY = 30# [19:50] <@CloverTheClever> Ctrl-S: if your downloader gets a connection error, sleep 10 and increase delay between attempts by a second GET_MAX_ATTEMPTS = 10 def setup_logging(log_file_path): # Setup logging (Before running any other code) # http://inventwithpython.com/blog/2012/04/06/stop-using-print-for-debugging-a-5-minute-quickstart-guide-to-pythons-logging-module/ assert( len(log_file_path) > 1 ) assert( type(log_file_path) == type("") ) global logger # Make sure output dir exists log_file_folder = os.path.dirname(log_file_path) if log_file_folder is not None: if not os.path.exists(log_file_folder): os.makedirs(log_file_folder) logger = logging.getLogger() logger.setLevel(logging.DEBUG) formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") fh = logging.FileHandler(log_file_path) fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) logger.addHandler(fh) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) logger.addHandler(ch) logging.debug("Logging started.") return def add_http(url): """Ensure a url starts with http://...""" if "http://" in url: return url elif "https://" in url: return url else: #case //derpicdn.net/img/view/... first_two_chars = url[0:2] if first_two_chars == "//": output_url = "https:"+url return output_url else: logging.error(repr(locals())) raise ValueError def deescape(html): # de-escape html # http://stackoverflow.com/questions/2360598/how-do-i-unescape-html-entities-in-a-string-in-python-3-1 deescaped_string = HTMLParser.HTMLParser().unescape(html) return deescaped_string def get(url): #try to retreive a url. If unable to return None object #Example useage: #html = get("") #if html: assert_is_string(url) deescaped_url = deescape(url) url_with_protocol = add_http(deescaped_url) #logging.debug( "getting url ", locals()) gettuple = getwithinfo(url_with_protocol) if gettuple: reply, info = gettuple return reply else: return def getwithinfo(url): """Try to retreive a url. If unable to return None objects Example useage: html = get("") if html: """ attemptcount = 0 while attemptcount < GET_MAX_ATTEMPTS: attemptcount = attemptcount + 1 if attemptcount > 1: delay(GET_RETRY_DELAY) logging.debug( "Attempt "+repr(attemptcount)+" for URL: "+repr(url) ) try: save_file(os.path.join("debug","get_last_url.txt"), url, True) r = br.open(url, timeout=100) info = r.info() reply = r.read() delay(GET_REQUEST_DELAY) # Save html responses for debugging #print info #print info["content-type"] if "html" in info["content-type"]: #print "saving debug html" save_file(os.path.join("debug","get_last_html.htm"), reply, True) else: save_file(os.path.join("debug","get_last_not_html.txt"), reply, True) # Retry if empty response and not last attempt if (len(reply) < 1) and (attemptcount < GET_MAX_ATTEMPTS): logging.error("Reply too short :"+repr(reply)) continue return reply,info except urllib2.HTTPError, err: logging.debug(repr(err)) if err.code == 404: logging.debug("404 error! "+repr(url)) return elif err.code == 403: logging.debug("403 error, ACCESS DENIED! url: "+repr(url)) return elif err.code == 410: logging.debug("410 error, GONE") return else: save_file(os.path.join("debug","HTTPError.htm"), err.fp.read(), True) continue except urllib2.URLError, err: logging.debug(repr(err)) if "unknown url type:" in err.reason: return else: continue except httplib.BadStatusLine, err: logging.debug(repr(err)) continue except httplib.IncompleteRead, err: logging.debug(repr(err)) continue except mechanize.BrowserStateError, err: logging.debug(repr(err)) continue except socket.timeout, err: logging.debug(repr( type(err) ) ) logging.debug(repr(err)) continue logging.critical("Too many repeated fails, exiting.") sys.exit()# [19:51] <@CloverTheClever> if it does it more than 10 times, quit/throw an exception upstream def save_file(filenamein,data,force_save=False): if not force_save: if os.path.exists(filenamein): logging.debug("file already exists! "+repr(filenamein)) return sanitizedpath = filenamein# sanitizepath(filenamein) foldername = os.path.dirname(sanitizedpath) if len(foldername) >= 1: if not os.path.isdir(foldername): os.makedirs(foldername) file = open(sanitizedpath, "wb") file.write(data) file.close() return def delay(basetime,upperrandom=0): #replacement for using time.sleep, this adds a random delay to be sneaky sleeptime = basetime + random.randint(0,upperrandom) #logging.debug("pausing for "+repr(sleeptime)+" ...") time.sleep(sleeptime) def crossplatform_path_sanitize(path_to_sanitize,remove_repeats=False): """Take a desired file path and chop away at it until it fits all platforms path requirements""" # Remove disallowed characters # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx windows_bad_chars = """/\\""" nix_bad_carhs = """/""" all_bad_chars = set(windows_bad_chars)+set(nix_bad_carhs) if remove_repeats: # Remove repeated characters, such as hyphens or spaces pass # Shorten if above filepath length limits windows_max_filepath_length = 255 nix_max_filepath_length = None # Ensure first and last characters of path segments are not whitespace path_segments = [] def import_list(listfilename="ERROR.txt"): """Read in a text file, return each line as a string in a list""" if os.path.exists(listfilename):# Check if there is a list query_list = []# Make an empty list list_file = open(listfilename, "rU") for line in list_file: if line[0] != "#" and line[0] != "\n":# Skip likes starting with '#' and the newline character if line[-1] == "\n":# Remove trailing newline if it exists stripped_line = line[:-1] else: stripped_line = line# If no trailing newline exists, we dont need to strip it query_list.append(stripped_line)# Add the username to the list list_file.close() return query_list else: # If there is no list, make one new_file_text = ("# Add one query per line, Full derpibooru search syntax MAY be available. Enter queries exactly as you would on the site.\n" + "# Any line that starts with a hash symbol (#) will be ignored.\n" + "# Search syntax help is available at https://derpibooru.org/search/syntax \n" + "# Example 1: -(pinkamena, +grimdark)\n" + "# Example 2: reversalis") list_file = open(listfilename, "w") list_file.write(new_file_text) list_file.close() return [] def append_list(lines,list_file_path="done_list.txt",initial_text="# List of completed items.\n",overwrite=False): # Append a string or list of strings to a file; If no file exists, create it and append to the new file. # Strings will be seperated by newlines. # Make sure we're saving a list of strings. if ((type(lines) is type(""))or (type(lines) is type(u""))): lines = [lines] # Ensure file exists and erase if needed if (not os.path.exists(list_file_path)) or (overwrite is True): list_file_segments = os.path.split(list_file_path) list_dir = list_file_segments[0] if list_dir: if not os.path.exists(list_dir): os.makedirs(list_dir) nf = open(list_file_path, "w") nf.write(initial_text) nf.close() # Write data to file. f = open(list_file_path, "a") for line in lines: outputline = line+"\n" f.write(outputline) f.close() return class config_handler(): def __init__(self,settings_path): self.settings_path = settings_path # Make sure settings folder exists settings_folder = os.path.dirname(self.settings_path) if settings_folder is not None: if not os.path.exists(settings_folder): os.makedirs(settings_folder) # Setup settings, these are static self.set_defaults() self.load_file(self.settings_path) self.save_settings(self.settings_path) self.handle_command_line_arguments() # Setup things that can change during program use self.load_deleted_submission_list()# list of submissions that are known to have been deleted return def set_defaults(self): """Set the defaults for settings, these will be overridden by settings from a file""" # derpibooru_dl.py # Login self.api_key = "Replace_this_with_your_API_key" # Download Settings self.reverse = False self.output_folder = "download"# Root path to download to self.download_submission_ids_list = True self.download_query_list = True self.output_long_filenames = False # Should we use the derpibooru supplied filename with the tags? !UNSUPPORTED! self.input_list_path = os.path.join("config","derpibooru_dl_tag_list.txt") self.done_list_path = os.path.join("config","derpibooru_done_list.txt") self.failed_list_path = os.path.join("config","derpibooru_failed_list.txt") self.save_to_query_folder = True # Should we save to multiple folders? self.skip_downloads = False # Don't retrieve remote submission files after searching self.sequentially_download_everything = False # download submission 1,2,3... self.go_backwards_when_using_sequentially_download_everything = False # when downloading everything in range mode should we go 10,9,8,7...? self.download_last_week = False # Download (approximately) the last weeks submissions self.skip_glob_duplicate_check = False # Skip glob.glob based duplicate check (only check if output file exists instead of scanning all output paths) self.skip_known_deleted = True # Skip submissions of the list of known deleted IDs self.deleted_submissions_list_path = os.path.join("config","deleted_submissions.txt") self.move_on_fail_verification = False # Should files be moved if verification of a submission fails? self.save_comments = False # Should comments be saved, uses more resources. # General settings self.show_menu = True # Should the text based menu system be used? self.hold_window_open = True # Should the window be kept open after all tasks are done? # Internal variables, these are set through this code only self.resume_file_path = os.path.join("config","resume.pkl") self.pointer_file_path = os.path.join("config","dl_everything_pointer.pkl") self.filename_prefix = "derpi_" self.sft_max_attempts = 10 # Maximum retries in search_for_tag() self.max_search_page_retries = 10 # maximum retries for a search page self.combined_download_folder_name = "combined_downloads"# Name of subfolder to use when saving to only one folder self.max_download_attempts = 10 # Number of times to retry a download before skipping self.verification_fail_output_path = "failed_verification" return def load_file(self,settings_path): """Load settings from a file""" config = ConfigParser.RawConfigParser() if not os.path.exists(settings_path): return config.read(settings_path) # derpibooru_dl.py # Login try: self.api_key = config.get("Login", "api_key") except ConfigParser.NoOptionError: pass # Download Settings try: self.reverse = config.getboolean("Download", "reverse") except ConfigParser.NoOptionError: pass try: self.output_folder = config.get("Download", "output_folder") except ConfigParser.NoOptionError: pass try: self.download_submission_ids_list = config.getboolean("Download", "download_submission_ids_list") except ConfigParser.NoOptionError: pass try: self.download_query_list = config.getboolean("Download", "download_query_list") except ConfigParser.NoOptionError: pass try: self.output_long_filenames = config.getboolean("Download", "output_long_filenames") except ConfigParser.NoOptionError: pass try: self.input_list_path = config.get("Download", "input_list_path") except ConfigParser.NoOptionError: pass try: self.done_list_path = config.get("Download", "done_list_path") except ConfigParser.NoOptionError: pass try: self.failed_list_path = config.get("Download", "failed_list_path") except ConfigParser.NoOptionError: pass try: self.save_to_query_folder = config.getboolean("Download", "save_to_query_folder") except ConfigParser.NoOptionError: pass try: self.skip_downloads = config.getboolean("Download", "skip_downloads") except ConfigParser.NoOptionError: pass try: self.sequentially_download_everything = config.getboolean("Download", "sequentially_download_everything") except ConfigParser.NoOptionError: pass try: self.go_backwards_when_using_sequentially_download_everything = config.getboolean("Download", "go_backwards_when_using_sequentially_download_everything") except ConfigParser.NoOptionError: pass try: self.download_last_week = config.getboolean("Download", "download_last_week") except ConfigParser.NoOptionError: pass try: self.skip_glob_duplicate_check = config.getboolean("Download", "skip_glob_duplicate_check") except ConfigParser.NoOptionError: pass try: self.skip_known_deleted = config.getboolean("Download", "skip_known_deleted") except ConfigParser.NoOptionError: pass try: self.deleted_submissions_list_path = config.get("Download", "deleted_submissions_list_path") except ConfigParser.NoOptionError: pass try: self.move_on_fail_verification = config.getboolean("Download", "move_on_fail_verification") except ConfigParser.NoOptionError: pass try: self.save_comments = config.getboolean("Download", "save_comments") except ConfigParser.NoOptionError: pass # General settings try: self.show_menu = config.getboolean("General", "show_menu") except ConfigParser.NoOptionError: pass try: self.hold_window_open = config.getboolean("General", "hold_window_open") except ConfigParser.NoOptionError: pass return def save_settings(self,settings_path): """Save settings to a file""" config = ConfigParser.RawConfigParser() config.add_section("Login") config.set("Login", "api_key", self.api_key ) config.add_section("Download") config.set("Download", "reverse", str(self.reverse) ) config.set("Download", "output_folder", self.output_folder ) config.set("Download", "download_submission_ids_list", str(self.download_submission_ids_list) ) config.set("Download", "download_query_list", str(self.download_query_list) ) config.set("Download", "output_long_filenames", str(self.output_long_filenames) ) config.set("Download", "input_list_path", self.input_list_path ) config.set("Download", "done_list_path", self.done_list_path ) config.set("Download", "failed_list_path", self.failed_list_path ) config.set("Download", "save_to_query_folder", str(self.save_to_query_folder) ) config.set("Download", "skip_downloads", str(self.skip_downloads) ) config.set("Download", "sequentially_download_everything", str(self.sequentially_download_everything) ) config.set("Download", "go_backwards_when_using_sequentially_download_everything", str(self.go_backwards_when_using_sequentially_download_everything) ) config.set("Download", "download_last_week", str(self.download_last_week) ) config.set("Download", "skip_glob_duplicate_check", str(self.skip_glob_duplicate_check) ) config.set("Download", "skip_known_deleted", str(self.skip_known_deleted) ) config.set("Download", "deleted_submissions_list_path", str(self.deleted_submissions_list_path) ) config.set("Download", "move_on_fail_verification", str(self.move_on_fail_verification) ) config.set("Download", "save_comments", str(self.save_comments) ) config.add_section("General") config.set("General", "show_menu", str(self.show_menu) ) config.set("General", "hold_window_open", str(self.hold_window_open) ) with open(settings_path, "wb") as configfile: config.write(configfile) return def handle_command_line_arguments(self): """Handle any command line arguments""" parser = argparse.ArgumentParser(description="DESCRIPTION FIELD DOES WHAT?") # Define what arguments are allowed menu_group = parser.add_mutually_exclusive_group() menu_group.add_argument("-m", "--menu", action="store_true",help="Show text based menu.")# Show text based menu menu_group.add_argument("-b", "--batch", action="store_true",help="Run in batch mode.")# Use batch mode parser.add_argument("-k", "--api_key",help="API Key.") parser.add_argument("-ids", "--download_submission_ids_list",help="download_submission_ids_list") parser.add_argument("-queries", "--download_query_list",help="download_query_list") parser.add_argument("-longfn", "--output_long_filenames",help="output_long_filenames") parser.add_argument("-qf", "--save_to_query_folder",help="save_to_query_folder") parser.add_argument("-skip", "--skip_downloads",help="skip_downloads") parser.add_argument("--sequentially_download_everything",help="sequentially_download_everything") parser.add_argument("--go_backwards_when_using_sequentially_download_everything",help="go_backwards_when_using_sequentially_download_everything") parser.add_argument("-ilp", "--input_list_path",help="input_list_path") parser.add_argument("--save_args_to_settings", action="store_true")# Write new settings to file # Store arguments to settings args = parser.parse_args() if args.menu: self.show_menu = True elif args.batch: self.show_menu = False if args.api_key: self.api_key = args.api_key if args.download_submission_ids_list: self.download_submission_ids_list = args.download_submission_ids_list if args.download_query_list: self.download_query_list = args.download_query_list if args.output_long_filenames: self.output_long_filenames = args.output_long_filenames if args.save_to_query_folder: self.save_to_query_folder = args.save_to_query_folder if args.skip_downloads: self.skip_downloads = args.skip_downloads if args.sequentially_download_everything: self.sequentially_download_everything = args.sequentially_download_everything if args.go_backwards_when_using_sequentially_download_everything: self.go_backwards_when_using_sequentially_download_everything = args.go_backwards_when_using_sequentially_download_everything if args.input_list_path: self.input_list_path = args.input_list_path # Write to settings file if needed. Must be done last if args.save_args_to_settings: self.save_settings() return def load_deleted_submission_list(self): """Load a list of known bad IDs from a file""" self.deleted_submissions_list = import_list(listfilename=self.deleted_submissions_list_path) return self.deleted_submissions_list def update_deleted_submission_list(self,submission_id): """Add a bad ID to the list in both ram and disk""" self.deleted_submissions_list.append(submission_id) append_list(submission_id, list_file_path=self.deleted_submissions_list_path, initial_text="# List of deleted IDs.\n", overwrite=False) return def assert_is_string(object_to_test): """Make sure input is either a string or a unicode string""" if( (type(object_to_test) == type("")) or (type(object_to_test) == type(u"")) ): return logging.critical(repr(locals())) raise(ValueError) def decode_json(json_string): """Wrapper for JSON decoding Return None object if known problem case occurs Return decoded data if successful Reraise unknown cases for caught exceptions""" assert_is_string(json_string) try: save_file(os.path.join("debug","last_json.json"), json_string, True) json_data = json.loads(json_string) return json_data except ValueError, err: # Retry if bad json recieved if "Unterminated string starting at:" in repr(err): logging.debug("JSON data invalid, failed to decode.") logging.debug(repr(json_string)) return elif "No JSON object could be decoded" in repr(err): if len(json_string) < 20: logging.debug("JSON string was too short!") logging.debug(repr(json_string)) return else: logging.critical(repr(locals())) raise(err) # Log locals and crash if unknown issue else: logging.critical(repr(locals())) raise(err) def read_file(path): """grab the contents of a file""" f = open(path, "r") data = f.read() f.close() return data def setup_browser(): #Initialize browser object to global variable "br" using cokie jar "cj" # Browser global br br = mechanize.Browser() br.set_cookiejar(cj) # Browser options br.set_handle_equiv(True) br.set_handle_gzip(True) br.set_handle_redirect(True) br.set_handle_referer(True) br.set_handle_robots(False) # Follows refresh 0 but not hangs on refresh > 0 br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1) # User-Agent (this is cheating, ok?) #br.addheaders = [("User-agent", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1")] #br.addheaders = [("User-agent", "Trixie is worst pony")]#[13:57] <%barbeque> as long as it's not something like "trixie is worst pony" #print "trixie is worst pony" br.addheaders = [("User-agent", "derpibooru_dl.py - https://github.com/woodenphone/Derpibooru-dl")] # Let's make it easy for the admins to see us so if something goes wrong we'll find out about it. return def search_for_query(settings,search_query): """Perform search for a query on derpibooru. Return a lost of found submission IDs""" assert_is_string(search_query) logging.debug("Starting search for query: "+repr(search_query)) found_submissions = [] for image in derpibooru.Search().key(settings.api_key).limit(None).query(search_query): found_submissions.append(image.id) return found_submissions def check_if_deleted_submission(json_dict): """Check whether the JSON Dict for a submission shows it as being deleted""" keys = json_dict.keys() if "deletion_reason" in keys: logging.error("Deleted submission! Reason: "+repr(json_dict["deletion_reason"])) return True elif "duplicate_of" in keys: logging.error("Deleted duplicate submission! Reason: "+repr(json_dict["duplicate_of"])) return True else: return False def copy_over_if_duplicate(settings,submission_id,output_folder): """Check if there is already a copy of the submission downloaded in the download path. If there is, copy the existing version to the suppplied output location then return True If no copy can be found, return False""" assert_is_string(submission_id) # Setting to override this function for speed optimisation on single folder output if settings.skip_glob_duplicate_check: return False # Generate expected filename pattern submission_filename_pattern = "*"+submission_id+".*" # Generate search pattern glob_string = os.path.join(settings.output_folder, "*", submission_filename_pattern) # Use glob to check for existing files matching the expected pattern #logging.debug("CALLING glob.glob, local vars: "+ repr(locals())) glob_matches = glob.glob(glob_string) #logging.debug("CALLED glob.glob, locals: "+repr(locals())) # Check if any matches, if no matches then return False if len(glob_matches) == 0: return False else: # If there is an existing version: for glob_match in glob_matches: # Skip any submission with the wrong ID match_submission_id = find_id_from_filename(settings, glob_match) if match_submission_id != submission_id: continue # If there is an existing version in the output path, nothing needs to be copied if output_folder in glob_match: return False else: # Copy over submission file and metadata JSON logging.info("Trying to copy from previous download: "+repr(glob_match)) # Check output folders exist # Build expected paths match_dir, match_filename = os.path.split(glob_match) expected_json_input_filename = submission_id+".json" expected_json_input_folder = os.path.join(match_dir, "json") expected_json_input_location = os.path.join(expected_json_input_folder, expected_json_input_filename) json_output_folder = os.path.join(output_folder, "json") json_output_filename = submission_id+".json" json_output_path = os.path.join(json_output_folder, json_output_filename) submission_output_path = os.path.join(output_folder,match_filename) # Redownload if a file is missing if not os.path.exists(glob_match): logging.debug("Submission file to copy is missing.") return False if not os.path.exists(expected_json_input_location): logging.debug("JSON file to copy is missing.") return False # Ensure output path exists if not os.path.exists(json_output_folder): os.makedirs(json_output_folder) if not os.path.exists(output_folder): os.makedirs(output_folder) logging.info("Copying files for submission: "+repr(submission_id)+" from "+repr(match_dir)+" to "+repr(output_folder)) # Copy over files try: # Copy submission file shutil.copy2(glob_match, submission_output_path) # Copy JSON shutil.copy2(expected_json_input_location, json_output_path) return True except IOError, err: logging.error("Error copying files!") logging.exception(err) return False def download_submission(settings,search_query,submission_id): """Download a submission from Derpibooru""" assert_is_string(search_query) submission_id = str(submission_id) setup_browser() query_for_filename = convert_query_for_path(settings,search_query) #logging.debug("Downloading submission:"+submission_id) # Build JSON paths json_output_filename = submission_id+".json" if settings.save_to_query_folder is True: json_output_path = os.path.join(settings.output_folder,query_for_filename,"json",json_output_filename) else: # Option to save to a single combined folder json_output_path = os.path.join(settings.output_folder,settings.combined_download_folder_name,"json",json_output_filename) # Check if download can be skipped # Check if JSON exists if os.path.exists(json_output_path): logging.debug("JSON for this submission already exists, skipping.") return # Build output folder path if settings.save_to_query_folder is True: output_folder = os.path.join(settings.output_folder,query_for_filename) else: # Option to save to a single combined folder output_folder = os.path.join(settings.output_folder,settings.combined_download_folder_name) # Check for dupliactes in download folder if copy_over_if_duplicate(settings, submission_id, output_folder): return # Option to skip loading remote submission files if settings.skip_downloads is True: return # Option to skip previously encountered deleted submissions if settings.skip_known_deleted: if submission_id in settings.deleted_submissions_list: return # Build JSON URL # Option to save comments, uses more resources. if settings.save_comments: json_url = "https://derpibooru.org/"+submission_id+".json?comments=true&key="+settings.api_key else: json_url = "https://derpibooru.org/"+submission_id+".json?key="+settings.api_key # Retry if needed download_attempt_counter = 0 while download_attempt_counter <= settings.max_download_attempts: download_attempt_counter += 1 if download_attempt_counter > 1: logging.debug("Attempt "+repr(download_attempt_counter)) # Load JSON URL json_page = get(json_url) if not json_page: continue # Convert JSON to dict json_dict = decode_json(json_page) if json_dict is None: continue # Check if submission is deleted if check_if_deleted_submission(json_dict): logging.debug("Submission was deleted.") logging.debug(repr(json_page)) settings.update_deleted_submission_list(submission_id) return # Extract needed info from JSON image_url = json_dict["image"] image_file_ext = json_dict["original_format"] image_height = json_dict["height"] image_width = json_dict["width"] # Build image output filenames if settings.output_long_filenames: # Grab the filename from the url by throwing away everything before the last forwardslash image_filename_crop_regex = """.+\/(.+)""" image_filename_search = re.search(image_filename_crop_regex, image_url, re.IGNORECASE|re.DOTALL) image_filename = image_filename_search.group(1) image_output_filename = settings.filename_prefix+image_filename+"."+image_file_ext else: image_output_filename = settings.filename_prefix+submission_id+"."+image_file_ext image_output_path = os.path.join(output_folder,image_output_filename) # Load image data authenticated_image_url = image_url+"?key="+settings.api_key logging.debug("Loading submission image. Height:"+repr(image_height)+", Width:"+repr(image_width)+", URL: "+repr(authenticated_image_url)) image_data = get(authenticated_image_url) if not image_data: return # Image should always be bigger than this, if it isn't we got a bad file if len(image_data) < 100: logging.error("Image data was too small! "+repr(image_data)) continue # Save image save_file(image_output_path, image_data, True) # Save JSON save_file(json_output_path, json_page, True) logging.debug("Download successful") return logging.error("Too many retries, skipping this submission.") logging.debug(repr(locals())) return def read_pickle(file_path): file_data = read_file(file_path) pickle_data = pickle.loads(file_data) return pickle_data def save_pickle(path,data): # Save data to pickle file # Ensure folder exists. if not os.path.exists(path): pickle_path_segments = os.path.split(path) pickle_dir = pickle_path_segments[0] if pickle_dir:# Make sure we aren't at the script root if not os.path.exists(pickle_dir): os.makedirs(pickle_dir) pf = open(path, "wb") pickle.dump(data, pf) pf.close() return def save_resume_file(settings,search_tag,submission_ids): # Save submissionIDs and search_tag to pickle logging.debug("Saving resume data pickle") # {"search_tag":"FOO", "submission_ids":["1","2"]} # Build dict resume_dict = { "search_tag":search_tag, "submission_ids":submission_ids } save_pickle(settings.resume_file_path, resume_dict) return def clear_resume_file(settings): # Erase pickle logging.debug("Erasing resume data pickle") if os.path.exists(settings.resume_file_path): os.remove(settings.resume_file_path) return def resume_downloads(settings): # Look for pickle of submissions to iterate over if os.path.exists(settings.resume_file_path): logging.debug("Resuming from pickle") # Read pickle: resume_dict = read_pickle(settings.resume_file_path) search_tag = resume_dict["search_tag"] submission_ids = resume_dict["submission_ids"] # Iterate over submissions download_submission_id_list(settings,submission_ids,search_tag) # Clear temp file clear_resume_file(settings) append_list(search_tag, settings.done_list_path) return search_tag else: return False def download_submission_id_list(settings,submission_ids,query): # Iterate over submissions submission_counter = 0 # If no submissions to save record failure if len(submission_ids) == 0: logging.warning("No submissions to save! Query:"+repr(query)) append_list(query, settings.failed_list_path, initial_text="# List of failed items.\n") if settings.reverse: logging.info("Reverse mode is active, reversing download order.") submission_ids.reverse() for submission_id in submission_ids: submission_counter += 1 # Only save pickle every 1000 items to help avoid pickle corruption if (submission_counter % 1000) == 0: cropped_submission_ids = submission_ids[( submission_counter -1 ):] save_resume_file(settings,query,cropped_submission_ids) logging.info("Now working on submission "+repr(submission_counter)+" of "+repr(len(submission_ids) )+" : "+repr(submission_id)+" for: "+repr(query) ) # Try downloading each submission download_submission(settings, query, submission_id) print "\n\n" return def save_pointer_file(settings,start_number,finish_number): """Save start and finish numbers to pickle""" logging.debug("Saving resume data pickle") # {"start_number":0, "finish_number":100} # Build dict resume_dict = { "start_number":start_number, "finish_number":finish_number } save_pickle(settings.pointer_file_path, resume_dict) return def clear_pointer_file(settings): """Erase range download pickle""" logging.debug("Erasing resume data pickle") if os.path.exists(settings.pointer_file_path): os.remove(settings.pointer_file_path) return def get_latest_submission_id(settings): """Find the most recent submissions ID""" logging.debug("Getting ID of most recent submission...") latest_submissions = [] for image in derpibooru.Search().key(settings.api_key): submission_id = image.id latest_submissions.append(submission_id) ordered_latest_submissions = sorted(latest_submissions) latest_submission_id = int(ordered_latest_submissions[0]) logging.debug("Most recent submission ID:"+repr(latest_submission_id)) return latest_submission_id def download_this_weeks_submissions(settings): """Download (about) one weeks worth of the most recent submissions""" logging.info("Now downloading the last week's submissions.") # Get starting number latest_submission_id = get_latest_submission_id(settings) # Calculate ending number one_weeks_submissions_number = 1000 * 7 # less than 1000 per day finish_number = latest_submission_id - one_weeks_submissions_number # Add a thousand to account for new submissions added during run logging.info("Downloading the last "+repr(one_weeks_submissions_number)+" submissions. Starting at "+repr(latest_submission_id)+" and stopping at "+repr(finish_number)) download_range(settings,latest_submission_id,finish_number) return def download_everything(settings): """Start downloading everything or resume downloading everything""" logging.info("Now downloading all submissions on the site") # Start downloading everything latest_submission_id = get_latest_submission_id(settings) start_number = 0 finish_number = latest_submission_id + 50000 # Add 50,000 to account for new submissions added during run if settings.go_backwards_when_using_sequentially_download_everything: # Swap start and finish numbers for backwards mode start_number, finish_number = latest_submission_id, start_number download_range(settings,start_number,finish_number) return def resume_range_download(settings): # Look for pickle of range to iterate over if os.path.exists(settings.pointer_file_path): logging.info("Resuming range from pickle") # Read pickle: resume_dict = read_pickle(settings.pointer_file_path) start_number = resume_dict["start_number"] finish_number = resume_dict["finish_number"] # Iterate over range download_range(settings,start_number,finish_number) return def download_range(settings,start_number,finish_number): """Try to download every submission within a given range If finish number is less than start number, run over the range backwards""" # If starting point is after end point, we're going backwards if(start_number > finish_number): backwards = True else: backwards = False assert(finish_number <= 2000000)# less than 2 million, 1,252,291 submissions as of 2016-09-18 assert(start_number >= 0)# First submission is ID 0 assert(type(finish_number) is type(1))# Must be integer assert(type(start_number) is type(1))# Must be integer total_submissions_to_attempt = abs(finish_number - start_number) logging.info("Downloading range: "+repr(start_number)+" to "+repr(finish_number)) # Iterate over range of id numbers submission_pointer = start_number loop_counter = 0 while (loop_counter <= total_submissions_to_attempt ): loop_counter += 1 assert(submission_pointer >= 0)# First submission is ID 0 assert(submission_pointer <= 2000000)# less than 2 million, 1,252,291 submissions as of 2016-09-18 assert(type(submission_pointer) is type(1))# Must be integer # Only save pickle every 1000 items to help avoid pickle corruption if (submission_pointer % 1000) == 0: save_pointer_file(settings, submission_pointer, finish_number) logging.info("Now working on submission "+repr(loop_counter)+" of "+repr(total_submissions_to_attempt)+", ID: "+repr(submission_pointer)+" for range download mode" ) # Try downloading each submission download_submission(settings, "RANGE_MODE", submission_pointer) print "\n\n" # Add/subtract from counter depending on mode if backwards: submission_pointer -= 1 else: submission_pointer += 1 # Clean up once everything is done clear_pointer_file(settings) return def download_ids(settings,query_list,folder): logging.info("Now downloading user set IDs.") submission_ids = [] for query in query_list: # remove invalid items if re.search("[^\d]",query): logging.debug("Not a submissionID! skipping.") continue else: submission_ids.append(query) download_submission_id_list(settings,submission_ids,folder) return def process_query(settings,search_query): """Download submissions for a tag on derpibooru""" assert_is_string(search_query) #logging.info("Processing tag: "+search_query) # Run search for query submission_ids = search_for_query(settings, search_query) # Save data for resuming if len(submission_ids) > 0: save_resume_file(settings,search_query,submission_ids) # Download all found items download_submission_id_list(settings,submission_ids,search_query) # Clear temp data clear_resume_file(settings) return def download_query_list(settings,query_list): logging.info("Now downloading user set tags/queries") counter = 0 for search_query in query_list: counter += 1 logging.info("Now proccessing query "+repr(counter)+" of "+repr(len(query_list))+": "+repr(search_query)) process_query(settings,search_query) append_list(search_query, settings.done_list_path) return def convert_tag_string_to_search_string(settings,query): """Fix a tag string for use as a search query string""" colons_fixed = query.replace("-colon-",":") dashes_fixed = colons_fixed.replace("-dash-","-") dots_fixed = dashes_fixed.replace("-dot-",".") return dots_fixed def convert_tag_list_to_search_string_list(settings,query_list): """Convert a whole list of queries to the new search format""" processed_queries = [] for raw_query in query_list: processed_query = convert_tag_string_to_search_string(settings,raw_query) processed_queries.append(processed_query) return processed_queries def convert_query_for_path(settings,query): """Convert a query to the old style -colon- format for filenames""" colons_fixed = query.replace(":", "-colon-") dashes_fixed = colons_fixed.replace("-", "-dash-") dots_fixed = dashes_fixed.replace(".", "-dot-") return dots_fixed def verify_folder(settings,target_folder): """Compare ID number and SHA512 hashes from submission JSON against their submission files, moving those that don't match to another folder""" logging.info("Verifying "+repr(target_folder)) files_list = walk_for_file_paths(target_folder) if len(files_list) < 1: logging.error("No files to verify!") return counter = 0 pass_count = 0 fail_count = 0 for file_path in files_list: counter += 1 logging.info("Verifying submission "+repr(counter)+" of "+repr(len(files_list))+" "+repr(file_path)) last_status = verify_saved_submission(settings,file_path) if last_status is True: pass_count += 1 elif last_status is False: fail_count += 1 logging.info("Finished verification with "+repr(pass_count)+" PASSED and "+repr(fail_count)+" FAILED for "+repr(target_folder)) return def walk_for_file_paths(start_path): """Use os.walk to collect a list of paths to files mathcing input parameters. Takes in a starting path and a list of patterns to check against filenames Patterns follow fnmatch conventions.""" logging.debug("Starting walk. start_path:"+repr(start_path)) assert(type(start_path) == type("")) matches = [] for root, dirs, files in os.walk(start_path): dirs[:] = [d for d in dirs if d not in ["json"]]# Scanning /json/ is far too slow for large folders, skip it. c = 1 logging.debug("root: "+root) for filename in files: c += 1 if (c % 1000) == 0: logging.debug("File # "+repr(c)+": "+repr(filename)) match = os.path.join(root,filename) matches.append(match) logging.debug("End folder") logging.debug("Finished walk.") return matches def verify_saved_submission(settings,target_file_path): """Compare ID number SHA512 hash from a submissions JSON with the submission file and move if not matching return True if pass, False if fail""" # http://www.pythoncentral.io/hashing-strings-with-python/ failed_test = False # Generate filenames and paths # Find out if we were given a JSON file if target_file_path[-5:].lower() == ".json".lower(): # We were given a JSON file, so convert the folder to the submission one json_folder = os.path.dirname(target_file_path) target_folder = os.path.dirname(json_folder) else: # Not a JSON file, use the folder we are in target_folder = os.path.dirname(target_file_path) submission_id = find_id_from_filename(settings, target_file_path) glob_submission_filename = settings.filename_prefix+submission_id+".*" glob_submission_path = os.path.join(target_folder, glob_submission_filename) # Use glob to find submission filename glob_matches = glob.glob(glob_submission_path) if len(glob_matches) != 1: failed_test = True if len(glob_matches) == 0: # No matches, this means fthe file is missing. logging.error("No submissions matched glob string!") logging.debug(repr(locals())) return False else: # More than one match, this should never happen. logging.error("More than one submission matched glob string!") logging.debug(repr(locals())) raise(ValueError) else: # If there is a single glob match, get the filename. assert(len(glob_matches) is 1) submission_path = glob_matches[0] submission_filename = os.path.basename(submission_path) submission_fail_folder = settings.verification_fail_output_path submission_fail_path = os.path.join(submission_fail_folder, submission_filename) json_filename = submission_id+".json" json_path = os.path.join(target_folder, "json", json_filename) json_fail_folder = os.path.join(settings.verification_fail_output_path, "json") json_fail_path = os.path.join(json_fail_folder, json_filename) json_string = read_file(json_path) decoded_json = decode_json(json_string) # Test the data # If ID < 6000 or type is .svg, skip tests. id_from_json = str(decoded_json["id"]) if int(id_from_json) < 6000: logging.info("ID below 6000, skipping tests due to unreliable hash.") return None if submission_path[-4:].lower() == ".svg".lower(): logging.info("Extention is .svg, skipping tests due to unreliable hash.") return None # Does the JSON provided hash match the image? json_hash = decoded_json["sha512_hash"] # http://www.pythoncentral.io/hashing-files-with-python/ BLOCKSIZE = 65536 hasher = hashlib.sha512() with open(submission_path, "rb") as afile: buf = afile.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = afile.read(BLOCKSIZE) file_hash = u"" + hasher.hexdigest()# convert to unicode if json_hash != file_hash: logging.error("Image hash did not match JSON "+repr(submission_path)) logging.debug(repr(file_hash)) logging.debug(repr(json_hash)) failed_test = True # Does the ID from the JSON match the image and JSON filenames? # Image filename id_from_image_filename = find_id_from_filename(settings, submission_path) if id_from_json != id_from_image_filename: logging.error("Image filename did not match JSON ID for "+repr(submission_path)) logging.debug(repr(id_from_json)+" vs "+repr(id_from_image_filename)) failed_test = True # JSON filename id_from_json_filename = find_id_from_filename(settings, json_path) if id_from_json != id_from_json_filename: logging.error("JSON filename did not match JSON ID "+repr(json_path)) failed_test = True # End of tests if failed_test is True: # Move if any test was failed logging.error("Verification FAIL: "+repr(target_file_path)) logging.debug(repr(locals())) if settings.move_on_fail_verification: logging.info("Moving sumbission and metadata to "+repr(settings.verification_fail_output_path)) try: # Move submission file if os.path.exists(submission_path): if not os.path.exists(submission_fail_folder): os.makedirs(submission_fail_folder) shutil.move(submission_path, submission_fail_path) # Move JSON file if os.path.exists(json_path): if not os.path.exists(json_fail_folder): os.makedirs(json_fail_folder) shutil.move(json_path, json_fail_path) return False except IOError, err: logging.error("Error copying files!") logging.exception(err) return False else: logging.info("Verification PASS: "+repr(target_file_path)) return True def find_id_from_filename(settings, file_path): """Extract submission ID from a file path or filename""" filename = os.path.basename(file_path) if filename[-5:].lower() == ".json".lower():# If the path ends in .json # JSON files always use the ID as the filename # 751715.json submission_id = filename[:-5] return submission_id else: # Not JSON # Expected filename types # Long derpibooru: # "image":"//derpicdn.net/img/view/2014/10/27/751715__safe_twilight+sparkle_rainbow+dash_pinkie+pie_fluttershy_rarity_applejack_comic_crossover_mane+six.jpeg", # Long derpibooru_dl: # derpi_751715__safe_twilight+sparkle_rainbow+dash_pinkie+pie_fluttershy_rarity_applejack_comic_crossover_mane+six.jpeg # Short derpibooru_dl: # derpi_751715.jpeg id_regex = """(\d+)(?:[_\.])""" id_search = re.search(id_regex, filename, re.IGNORECASE|re.DOTALL) submission_id = id_search.group(1) return submission_id def verify_api_key(api_key): """Test to see if a given API key looks real. Return True if it looks okay, False if it looks bad""" assert(type(api_key) is type(""))# If this is not a string bad things will probably happen, and something has most likely gone wrong in the import code key_is_valid = True # Test for the default string if api_key == "Replace_this_with_your_API_key": logging.error("API key was default (No key was set).") key_is_valid = False # Test length of key # [21:07] <@CloverTheClever> Ctrl-S: it'll be alphanumeric and fixed size iirc # Known valid lengths: 20 if (len(api_key) != 20): logging.error("API key length invalid. Should be 20 chars. Length: "+repr(len(api_key))) key_is_valid = False # Test if any characters outside those allowed are in the string # "<%byte[]> it's generated with SecureRandom.urlsafe_base64(rlength).tr('lIO0', 'sxyz') # rlength is 15" # http://apidock.com/ruby/SecureRandom/urlsafe_base64/class # http://stackoverflow.com/questions/89909/how-do-i-verify-that-a-string-only-contains-letters-numbers-underscores-and-da # Remove any characters that are allowed, if any characters remain we have invalid characters in the string. allowed_characters = string.ascii_letters + string.digits + "-_"# http://apidock.com/ruby/SecureRandom/urlsafe_base64/class invalid_characters_in_key = set(api_key) - set(allowed_characters) if invalid_characters_in_key: logging.error("API key contains invalid characters.") logging.debug("Invalid characters found: "+repr(invalid_characters_in_key)) key_is_valid = False # Check ig it's the first or last bit that's wrong. if set(api_key[:5]) - set(allowed_characters): logging.error("Problem in first 5 characters") if set(api_key[-5:]) - set(allowed_characters): logging.error("Problem in last 5 characters") # Try actually loading something with the key. A search for "explicit" will fail if key is invalid. key_test_url = "https://derpibooru.org/search.json?q=explicit&key="+api_key test_response = get(key_test_url) if len(test_response) <= len("""{"search":[]}"""): logging.error("Search for 'explicit' failed using this key! Check key and account display settings!") key_is_valid = False test_response_dict = decode_json(test_response) # If no test has failed, we have a valid key. if key_is_valid: logging.debug("API Key looks fine.") else: logging.warning("API key looks invalid!") logging.debug("First 5 chars of key:"+repr(api_key[:5])) logging.debug("First 5 chars of key:"+repr(api_key[-5:])) print("The API key you entered is: "+api_key+" This message is not recorded to the log file.") return key_is_valid # Boolean can be passed out as-is def print_menu_options(): """Main info text for menu""" print "1. Download the last week or so's submissions." print "2. Enter and download a range of submission IDs." print "3. Enter and download the results of a search query" print "4. Download the results of each query and submission ID in the download list" print "5. Run downloads automatically based on settings file." print "X. Exit." return def menu_range_prompt(settings,input_file_list): """Download user specified range""" print "Enter ID to start from then press enter. Leave blank to cancel." start_id_input = raw_input() try: start_id = int(start_id_input) except ValueError, err: logging.info("Canceled.") return print "Enter ID to stop at then press enter. Leave blank to cancel." stop_id_input = raw_input() try: stop_id = int(stop_id_input) except ValueError, err: logging.info("Canceled.") return download_range(settings,start_id,stop_id) return def console_menu(settings,input_file_list): """Simple text based menu""" menu_open = True while menu_open: print_menu_options() print "Enter an option then press return" menu_data = raw_input() logging.debug("Menu user input:"+repr(menu_data)) if menu_data == "1": # Download the last week's submissions download_this_weeks_submissions(settings) continue elif menu_data == "2": # Download user specified range menu_range_prompt(settings,input_file_list) continue elif menu_data == "3": # Download a user specified query. print "Enter your search query then press enter. Leave empty to cancel." search_query = raw_input() logging.debug("Query: "+repr(search_query)) if len(search_query) > 0: process_query(settings,search_query) append_list(search_query, settings.done_list_path) continue elif menu_data == "4": # Run over download list download_query_list(settings,input_file_list) continue elif menu_data == "5": # Run automatic batch mode run_batch_mode(settings,input_file_list) continue elif (menu_data == "x") or (menu_data == "X"): logging.info("Exiting menu.") return else: print "Invalid selection, try again." continue return def run_batch_mode(settings,input_file_list): """Run downloads based on settings without the need for user interaction""" # Begin new download operations # Ordered based on expected time to complete operations. # Download individual submissions if settings.download_submission_ids_list: download_ids(settings,input_file_list,"from_list") # Download last week mode (~7,000 items) if settings.download_last_week: download_this_weeks_submissions(settings) # Process each search query if settings.download_query_list: download_query_list(settings,input_file_list) # Download evrything mode if settings.sequentially_download_everything: download_everything(settings) return def remove_before_last_query(resumed_query,input_file_list): """Crop list of queries to exclude everything upto and including the one that was resumed""" if resumed_query is not False: if resumed_query in input_file_list: # Skip everything before and including resumed tag logging.info("Skipping all items before the resumed tag: "+repr(resumed_query)) #logging.debug(repr(tag_list)) position_of_resumed_query = input_file_list.index(resumed_query) position_to_keep_after = position_of_resumed_query + 1 input_file_list = input_file_list[position_to_keep_after:] return input_file_list def main(): # Load settings settings = config_handler(os.path.join("config","derpibooru_dl_config.cfg")) valid_api_key = verify_api_key(settings.api_key) if not valid_api_key: logging.warning("Using API key that looks bad, some images may not be available!") logging.warning("Check that you entered your API key correctly.") if settings.api_key == "Replace_this_with_your_API_key": # Remove unset key logging.warning("No API key set, weird things may happen.") settings.api_key = "" # Load tag list raw_input_file_list = import_list(settings.input_list_path) # Fix input list input_file_list = convert_tag_list_to_search_string_list(settings, raw_input_file_list) #submission_list = import_list("config\\derpibooru_dl_submission_id_list.txt") # DEBUG #download_submission(settings,"DEBUG","263139") #print search_for_tag(settings,"test") #process_tag(settings,"test") #copy_over_if_duplicate(settings,"134533","download\\flitterpony") #a = read_pickle("debug\\locals.pickle") #print "" #return # /DEBUG # Handle resuming query download operations logging.info("Attempting to resume any failed downloads.") resumed_query = resume_downloads(settings) input_file_list = remove_before_last_query(resumed_query,input_file_list) # Resume range operations resume_range_download(settings) # Show menu if option set if settings.show_menu: # Interactive mode. console_menu(settings,input_file_list) else: # Automatic batch mode. run_batch_mode(settings,input_file_list) logging.info("All tasks done, exiting.") if settings.hold_window_open: logging.info("Press enter to close window.") raw_input() return if __name__ == "__main__": # Setup logging setup_logging(os.path.join("debug","derpibooru_dl_log.txt")) try: cj = cookielib.LWPCookieJar() setup_browser() main() except Exception, err: # Log exceptions logger.critical("Unhandled exception!") logger.critical(repr( type(err) ) ) logging.exception(err) logging.info( "Program finished.") <file_sep>/deduplicate_downloads.py #------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: new # # Created: 28/03/2014 # Copyright: (c) new 2014 # Licence: <your licence> #------------------------------------------------------------------------------- #!/usr/bin/env python import derpibooru_dl import logging import os import glob import re import shutil import time import ConfigParser class settings_handler: def __init__(self,settings_path=os.path.join("config","derpibooru_deduplicate_config.cfg")): self.set_defaults() self.load_file(settings_path) self.save_settings(settings_path) return def set_defaults(self): self.downloads_folder = "download"# Folder to process self.output_folder = os.path.join(self.downloads_folder,"combined_downloads")# Folder to output to self.use_tag_list = True# Use tag list instead of processing everything self.move_files = False# Move files instead of copying them self.reverse = False self.input_list_path = os.path.join("config","tags_to_deduplicate.txt") self.done_list_path = os.path.join("config","derpibooru_deduplicate_done_list.txt") self.combined_download_folder_name = "combined_downloads"# Name of subfolder to use when saving to only one folder self.slow_for_debug = False # Pause between folders and files self.filename_prefix = "derpi_" return def load_file(self,settings_path): config = ConfigParser.RawConfigParser() if not os.path.exists(settings_path): return config.read(settings_path) # General settings try: self.downloads_folder = config.get('Settings', 'downloads_folder') except ConfigParser.NoOptionError: pass try: self.output_folder = config.get('Settings', 'output_folder') except ConfigParser.NoOptionError: pass try: self.use_tag_list = config.getboolean('Settings', 'use_tag_list') except ConfigParser.NoOptionError: pass try: self.move_files = config.getboolean('Settings', 'move_files') except ConfigParser.NoOptionError: pass try: self.reverse = config.getboolean('Settings', 'reverse') except ConfigParser.NoOptionError: pass try: self.input_list_path = config.get('Settings', 'input_list_path') except ConfigParser.NoOptionError: pass try: self.done_list_path = config.get('Settings', 'done_list_path') except ConfigParser.NoOptionError: pass try: self.combined_download_folder_name = config.get('Settings', 'combined_download_folder_name') except ConfigParser.NoOptionError: pass try: self.slow_for_debug = config.getboolean('Settings', 'slow_for_debug') except ConfigParser.NoOptionError: pass return def save_settings(self,settings_path): config = ConfigParser.RawConfigParser() config.add_section('Settings') config.set('Settings', 'downloads_folder', self.downloads_folder ) config.set('Settings', 'output_folder', self.output_folder ) config.set('Settings', 'use_tag_list', str(self.use_tag_list) ) config.set('Settings', 'move_files', str(self.move_files) ) config.set('Settings', 'reverse', str(self.reverse) ) config.set('Settings', 'input_list_path', str(self.input_list_path) ) config.set('Settings', 'done_list_path', str(self.done_list_path) ) config.set('Settings', 'combined_download_folder_name', str(self.combined_download_folder_name) ) config.set('Settings', 'slow_for_debug', str(self.slow_for_debug) ) with open(settings_path, 'wb') as configfile: config.write(configfile) return def pause(delay_time): logging.debug("Pausing for "+str(delay_time)+" seconds...") time.sleep(delay_time) logging.debug("Resuming operation") def process_submission_data_tuple(settings,submission_data_tuple): """Take a tuple containing: 1. Submission file location 2. Submission info location 3. Submission ID number And move/copy the submission files to the output folder""" # Build expected paths image_input_filepath, json_input_filepath, submission_id = submission_data_tuple input_dir, image_filename = os.path.split(image_input_filepath) json_output_filename = os.path.split(json_input_filepath)[1] json_output_folder = os.path.join(settings.output_folder, "json") json_output_path = os.path.join(json_output_folder, json_output_filename) image_output_path = os.path.join(settings.output_folder,image_filename) # Ensure output path exists if not os.path.exists(json_output_folder): os.makedirs(json_output_folder) if not os.path.exists(settings.output_folder): os.makedirs(settings.output_folder) # Check that both files exist in the input location and skip if either is missing # Debug warning if overwriting existing file in output dir: if os.path.exists(image_output_path): logging.debug("Overwriting output image file.") if os.path.exists(json_output_path): logging.debug("Overwriting output JSON file.") # Depending on mode, wither copy or move files to output location if settings.move_files is True: logging.info("Moving files for submission: "+submission_id+" from "+input_dir+" to "+settings.output_folder) try: # Copy submission file shutil.move(image_input_filepath, image_output_path) # Copy JSON shutil.move(json_input_filepath, json_output_path) return True except IOError, err: logging.error("Error copying files!") logging.exception(err) return False else: # Copy over files logging.info("Copying files for submission: "+submission_id+" from "+input_dir+" to "+settings.output_folder) try: # Copy submission file shutil.copy2(image_input_filepath, image_output_path) # Copy JSON shutil.copy2(json_input_filepath, json_output_path) return True except IOError, err: logging.error("Error copying files!") logging.exception(err) return False def generate_image_tuples(settings,input_folder_path): """Generate a list of tuples of image file paths and their id numbers. e.g. ("download\\derpi_12345.jpg", "12345")""" # generate glob string for images image_glob_string = os.path.join(input_folder_path, settings.filename_prefix+"*") # list image files in folder image_files_list = glob.glob(image_glob_string) #print "image_files_list", image_files_list # Extract submission ids from filenames image_tuples = [] for image_file_path in image_files_list: image_id_regex = settings.filename_prefix+"(\d+)" image_id_search = re.search(image_id_regex,image_file_path) if image_id_search: image_id = image_id_search.group(1) image_tuple = (image_file_path, image_id) image_tuples.append(image_tuple) #print "image_tuples", image_tuples return image_tuples def generate_json_tuples(settings,input_folder_path): """Generate a list of tuples of json file paths and their id numbers. e.g. ("download\\json\\12345.json", "12345")""" # Generate JSON glob string json_glob_string = os.path.join(input_folder_path,"json","*.json") # list json files json_files_list = glob.glob(json_glob_string) #print "json_files_list", json_files_list # Extract JSON ids json_tuples = [] for json_file_path in json_files_list: json_id_regex = "(\d+)\.json" json_id_search = re.search(json_id_regex,json_file_path) if json_id_search: json_id = json_id_search.group(1) json_tuple = (json_file_path, json_id) json_tuples.append(json_tuple) #print "json_tuples", json_tuples return json_tuples def join_submission_data_lists(settings,image_tuples,json_tuples): # Data tuple formats: # image_tuple = (image_file_path, image_id) # json_tuple = (json_file_path, json_id) # joined_file_tuple = (image_file_path, json_file_path, image_id) # Sort and join tuples joined_files_tuples = [] for image_tuple in image_tuples: image_id = image_tuple[1] for json_tuple in json_tuples: json_id = json_tuple[1] if json_id == image_id: image_file_path = image_tuple[0] json_file_path = json_tuple[0] joined_file_tuple = (image_file_path, json_file_path, image_id) joined_files_tuples.append(joined_file_tuple) #print "joined_files_tuples", joined_files_tuples return joined_files_tuples def generate_submission_data_tuples(settings,input_folder_path): """Build a list of tuples for submissions in the target folder""" logging.debug("Analysing input data...") image_tuples = generate_image_tuples(settings,input_folder_path) json_tuples = generate_json_tuples(settings,input_folder_path) # join lists into pairs of filepaths for each submission and its associated JSON submission_data_tuples = join_submission_data_lists(settings,image_tuples,json_tuples) return submission_data_tuples def process_folder(settings,folder_name): input_folder_path = os.path.join(settings.downloads_folder,folder_name) # Make sure input folder is valid if not os.path.exists(input_folder_path): logging.error("specified folder does not exist, cannot process it."+input_folder_path) return if input_folder_path == settings.output_folder: logging.error("Cannot deduplicate output folder!") return logging.info("Deduplicating from: "+str(input_folder_path)) # Buld pairs of submission + metadata files to process submission_data_tuples = generate_submission_data_tuples(settings,input_folder_path) # Process each pair counter = 0 number_of_tuples = len(submission_data_tuples) for submission_data_tuple in submission_data_tuples: counter +=1 logging.debug("Processing submission "+str(counter)+" of "+str(number_of_tuples)) process_submission_data_tuple(settings, submission_data_tuple) if settings.slow_for_debug: pause(1) # Add folder to done list derpibooru_dl.append_list(folder_name, list_file_path=settings.done_list_path, initial_text="# List of completed items.\n", overwrite=False) return def process_folders(settings,folder_names): logging.debug("Folders to deduplicate: "+str(folder_names)) logging.info("Starting to deduplicate folders") counter = 0 number_of_folders = len(folder_names) for folder_name in folder_names: counter += 1 logging.info("Deduplicating folder "+str(counter)+" of "+str(number_of_folders)+" : "+str(folder_name)) process_folder(settings,folder_name) if settings.slow_for_debug: pause(60) return def list_subfolders(start_path): for root, dirs, files in os.walk(start_path): return dirs def main(): settings = settings_handler(os.path.join("config","derpibooru_deduplicate_config.cfg")) if settings.use_tag_list is True: # Load todo list tag_list = derpibooru_dl.import_list(settings.input_list_path) elif settings.use_tag_list is False: # Generate list of all folders in download folder tag_list = list_subfolders(settings.downloads_folder) process_folders(settings,tag_list) if __name__ == '__main__': # Setup logging derpibooru_dl.setup_logging(os.path.join("debug","derpibooru_deduplicate_log.txt")) try: main() except Exception, err: # Log exceptions logging.critical("Unhandled exception!") logging.critical(str( type(err) ) ) logging.exception(err) logging.info( "Program finished.") #raw_input("Press return to close") <file_sep>/split_to_tag_folders.py #------------------------------------------------------------------------------- # Name: copy_to_tag_folders # Purpose: # # Author: new # # Created: 08/07/2014 # Copyright: (c) new 2014 # Licence: <your licence> #------------------------------------------------------------------------------- #!/usr/bin/env python import os import logging import derpibooru_dl def add_tags_to_dict(settings,tags_db_dict,json_id,json_path,tags): """Add the specified tags to the dict and return the new one Format is: tag_db = {processed:{ID1:JSON_Path1,ID2:JSON_Path2,...} tags:{tag1:{ID1:JSON_path1,ID2:JSON_Path2}, tag2:{....},...}""" for tag in tags: # Ensure dict for tag exists try: tags_db_dict["tags"][tag] except KeyError: tags_db_dict["tags"][tag] = {} # Add entry to tag dict tags_db_dict["tags"][tag][json_id] = json_path return tags_db_dict def read_tags_from_json_file(json_path): """Open a derpibooru .JSON file and return the tags from it""" # Read JSON json_string = derpibooru_dl.read_file(json_path) decoded_json = derpibooru_dl.decode_json(json_string) # Grab tags tag_string_from_json = decoded_json["tags"] tags_from_json = tag_string_from_json.split(",") #logging.debug(tags_from_json) return tags_from_json def build_tag_db(settings,tag_db_dict={}): """Build a db of ids and tags. If given, add to existing DB dict, otherwise build one from scratch. Format is: tag_db = {processed:{ID1:JSON_Path1,ID2:JSON_Path2,...} tags:{tag1:{ID1:JSON_path1,ID2:JSON_Path2}, tag2:{....},...}""" building_new_db = (len(tag_db_dict) is len({})) if building_new_db: # Initialize dict tag_db_dict["processed"] = {} tag_db_dict["tags"] = {} logging.debug("Building tag DB") # Scan target folder for .JSON files target_folder = os.path.join(settings.output_folder, settings.combined_download_folder_name) number_of_ids_in_dict = len(tag_db_dict["processed"]) logging.debug("number of keys in processed listing dict:"+str(number_of_ids_in_dict)) # Use xrange() to generate paths because it's faster than os.walk() for large folders for number in xrange(number_of_ids_in_dict,1000000): # Generate path to the json file submission_id = str(number) json_filename = submission_id+".json" json_path = os.path.join(target_folder, "json", json_filename) if os.path.exists(json_path): # Check if id is in processed dict try: #tag_db = {processed:{ID1:JSON_Path1,ID2:JSON_Path2,...},...} dummy_path = tag_db_dict["processed"][submission_id] # True; ID has been processed. pass except KeyError: # False; ID has not been processed. logging.debug("New JSON found, reading. "+json_path) # If ID is not yet processed, read tags from json tags = read_tags_from_json_file(json_path) # add to dict tag_db_dict = add_tags_to_dict(settings,tag_db_dict,submission_id,json_path,tags) else: logging.error("JSON not found for id! "+json_path) #Once all paths are processed, return finished dict return tag_db_dict def load_tag_db_pickle(settings): """Either load a valid tag DB from pickle or return an empty dict""" # Check for existing DB in pickle path if os.path.exists(settings.tag_splitter_tag_db_file_path): data_from_file = read_pickle(settings.tag_splitter_tag_db_file_path) if type(data_from_file == type({})): return data_from_file logging.error("Error loading tag db from file! Using an empty one instead.") # If any test fails, return empty dict return {} def get_tag_db(settings): """Get a dictionary containing the tag info through whatever means needed. Format is: tag_db = {processed:{ID1:JSON_Path1,ID2:JSON_Path2,...} tags:{tag1:{ID1:JSON_path1,ID2:JSON_Path2}, tag2:{....},...}""" # tag_db = { tag1:{ID1:path1,ID2:Path2},tag2:{....},...} # Try loading from saved pickle tag_db_dict_from_file = load_tag_db_pickle(settings) if settings.tag_splitter_update_tag_db: new_tag_db_dict = build_tag_db(settings,tag_db_dict_from_file) return new_tag_db_dict else: return tag_db_dict_from_file def copy_tag(settings,tag_db_dict,tag): """Copy all files matching the given tag to a folder /<tag>/ in the output folder. Format is: tag_db = {processed:{ID1:JSON_Path1,ID2:JSON_Path2,...} tags:{tag1:{ID1:JSON_path1,ID2:JSON_Path2}, tag2:{....},...}""" tag_ids_dict = tag_db_dict["tags"][tag] id_to_copy = tag_ids_dict.keys() logging.debug("About to copy these items to "+tag+": "+str(id_to_copy)) output_folder = os.path.join(settings.output_folder,tag) for id_to_copy in ids_to_copy: derpibooru_dl.copy_over_if_duplicate(settings,id_to_copy,output_folder) def copy_tag_list(settings): # Read tag list from config folder user_input_list = derpibooru_dl.import_list(listfilename=settings.tag_splitter_tag_list_path) # Get database of tags tag_db_dict = get_tag_db(settings) # Iterate through user input list counter = 0 for tag in user_input_list: tag += u""# convert input to unicode counter += 1 logging.debug("Now copying tag "+str(counter)+" of "+str(len(user_input_list))+":"+tag) tag_db_dict = copy_tag(settings,tag_db_dict,tag) logging.info("Done copying tags") pass def main(): derpibooru_dl.setup_logging("debug\\tag_splitter_log.txt") # Load settings settings = derpibooru_dl.config_handler(os.path.join("config","derpibooru_dl_config.cfg")) # Settings to impliment in main settings TODO settings.tag_splitter_tag_db_file_path = "config\\tag_db.pkl" settings.tag_splitter_tag_list_path = "config\\tags_to_split.txt" settings.tag_splitter_update_tag_db = False settings.tag_splitter_speedhack = True # Speedhacks for tag splitter, for dev's computer only copy_tag_list(settings) if __name__ == '__main__': main() <file_sep>/verify_downloads.py #------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: new # # Created: 25/06/2014 # Copyright: (c) new 2014 # Licence: <your licence> #------------------------------------------------------------------------------- #!/usr/bin/env python from derpibooru_dl import * def main(): # Load settings settings = config_handler(os.path.join("config","derpibooru_dl_config.cfg")) verify_folder(settings, settings.output_folder) if __name__ == '__main__': # Setup logging setup_logging(os.path.join("debug","derpibooru_verify_log.txt")) try: #cj = cookielib.LWPCookieJar() #setup_browser() main() except Exception, err: # Log exceptions logging.critical("Unhandled exception!") logging.critical(str( type(err) ) ) logging.exception(err) logging.info( "Program finished.") #raw_input("Press return to close") <file_sep>/test_derpibooru_dl.py #------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: new # # Created: 08/02/2014 # Copyright: (c) new 2014 # Licence: <your licence> #------------------------------------------------------------------------------- #!/usr/bin/env python def main(): pass if __name__ == '__main__': # Setup logging main()
7401689e8466f9451a0a07883ed552651907722a
[ "Markdown", "Python" ]
8
Python
woodenphone/Derpibooru-dl
b872edee0437326acc7ffbd994a672af32d1a6da
b2ee7e5b6c7f6ad6c5980bc48686a5de8886ceed
refs/heads/master
<file_sep>package main import ( "context" "strconv" "time" "github.com/dgrijalva/jwt-go/v4" "github.com/google/uuid" authpb "github.com/loadlab-go/pkg/proto/auth" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) type jwtSvc struct { authpb.UnimplementedJWTServer Key []byte } func (s *jwtSvc) GenerateJWT(_ context.Context, req *authpb.GenerateJWTRequest) (*authpb.GenerateJWTResponse, error) { now := time.Now() jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS512, jwt.StandardClaims{ ID: uuid.New().String(), Issuer: "authmgr", IssuedAt: jwt.NewTime(float64(now.Second())), NotBefore: jwt.NewTime(float64(now.Unix()) - 30), ExpiresAt: jwt.NewTime(float64(now.AddDate(0, 0, 1).Unix())), Subject: strconv.FormatInt(req.Id, 10), }) token, err := jwtToken.SignedString(s.Key) if err != nil { logger.Warn("sign failed", zap.Error(err)) return nil, status.Errorf(codes.Aborted, "sign failed: %v", err) } return &authpb.GenerateJWTResponse{Token: token}, nil } func (s *jwtSvc) ValidateJWT(_ context.Context, req *authpb.ValidateJWTRequest) (*authpb.ValidateJWTResponse, error) { jwtToken, err := jwt.ParseWithClaims(req.Token, &jwt.StandardClaims{}, func(t *jwt.Token) (interface{}, error) { return s.Key, nil }) if err != nil { logger.Warn("jwt parse failed", zap.Error(err)) return nil, status.Errorf(codes.Aborted, "jwt parse failed: %v", err) } claims := jwtToken.Claims.(*jwt.StandardClaims) return &authpb.ValidateJWTResponse{ Aud: claims.Audience, Exp: claims.ExpiresAt.Unix(), Jti: claims.ID, Iat: claims.IssuedAt.Unix(), Iss: claims.Issuer, Nbf: claims.NotBefore.Unix(), Sub: claims.Subject, }, nil }
abcd9e18ec1d424f1c67da90e78635dcf7077594
[ "Go" ]
1
Go
loadlab-go/authsvc
bdc2166a7d32e65e7a39923477763481a11dc85c
0f4da3dcf29bf7bcec5fc067c1f6b548a4556ddb
refs/heads/master
<file_sep>#include "firestore/src/android/document_snapshot_android.h" #include <jni.h> #include <utility> #include "app/src/util_android.h" #include "firestore/src/android/document_reference_android.h" #include "firestore/src/android/field_path_android.h" #include "firestore/src/android/field_value_android.h" #include "firestore/src/android/server_timestamp_behavior_android.h" #include "firestore/src/android/snapshot_metadata_android.h" #include "firestore/src/android/util_android.h" #include "firestore/src/include/firebase/firestore.h" namespace firebase { namespace firestore { using ServerTimestampBehavior = DocumentSnapshot::ServerTimestampBehavior; // clang-format off #define DOCUMENT_SNAPSHOT_METHODS(X) \ X(GetId, "getId", "()Ljava/lang/String;"), \ X(GetReference, "getReference", \ "()Lcom/google/firebase/firestore/DocumentReference;"), \ X(GetMetadata, "getMetadata", \ "()Lcom/google/firebase/firestore/SnapshotMetadata;"), \ X(Exists, "exists", "()Z"), \ X(GetData, "getData", \ "(Lcom/google/firebase/firestore/DocumentSnapshot$" \ "ServerTimestampBehavior;)Ljava/util/Map;"), \ X(Contains, "contains", \ "(Lcom/google/firebase/firestore/FieldPath;)Z"), \ X(Get, "get", \ "(Lcom/google/firebase/firestore/FieldPath;" \ "Lcom/google/firebase/firestore/DocumentSnapshot$" \ "ServerTimestampBehavior;)Ljava/lang/Object;") // clang-format on METHOD_LOOKUP_DECLARATION(document_snapshot, DOCUMENT_SNAPSHOT_METHODS) METHOD_LOOKUP_DEFINITION(document_snapshot, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/DocumentSnapshot", DOCUMENT_SNAPSHOT_METHODS) Firestore* DocumentSnapshotInternal::firestore() const { FIREBASE_ASSERT(firestore_->firestore_public() != nullptr); return firestore_->firestore_public(); } const std::string& DocumentSnapshotInternal::id() const { if (!cached_id_.empty()) { return cached_id_; } JNIEnv* env = firestore_->app()->GetJNIEnv(); jstring id = static_cast<jstring>(env->CallObjectMethod( obj_, document_snapshot::GetMethodId(document_snapshot::kGetId))); cached_id_ = util::JniStringToString(env, id); CheckAndClearJniExceptions(env); return cached_id_; } DocumentReference DocumentSnapshotInternal::reference() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject reference = env->CallObjectMethod( obj_, document_snapshot::GetMethodId(document_snapshot::kGetReference)); DocumentReferenceInternal* internal = new DocumentReferenceInternal{firestore_, reference}; env->DeleteLocalRef(reference); CheckAndClearJniExceptions(env); return DocumentReference{internal}; } SnapshotMetadata DocumentSnapshotInternal::metadata() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject metadata = env->CallObjectMethod( obj_, document_snapshot::GetMethodId(document_snapshot::kGetMetadata)); SnapshotMetadata result = SnapshotMetadataInternal::JavaSnapshotMetadataToSnapshotMetadata( env, metadata); CheckAndClearJniExceptions(env); return result; } bool DocumentSnapshotInternal::exists() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jboolean exists = env->CallBooleanMethod( obj_, document_snapshot::GetMethodId(document_snapshot::kExists)); CheckAndClearJniExceptions(env); return static_cast<bool>(exists); } MapFieldValue DocumentSnapshotInternal::GetData( ServerTimestampBehavior stb) const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject stb_enum = ServerTimestampBehaviorInternal::ToJavaObject(env, stb); jobject map_value = env->CallObjectMethod( obj_, document_snapshot::GetMethodId(document_snapshot::kGetData), stb_enum); CheckAndClearJniExceptions(env); FieldValueInternal value(firestore_, map_value); env->DeleteLocalRef(map_value); return value.map_value(); } FieldValue DocumentSnapshotInternal::Get(const FieldPath& field, ServerTimestampBehavior stb) const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject field_path = FieldPathConverter::ToJavaObject(env, field); // Android returns null for both null fields and nonexistent fields, so first // use contains() to check if the field exists. jboolean contains_field = env->CallBooleanMethod( obj_, document_snapshot::GetMethodId(document_snapshot::kContains), field_path); CheckAndClearJniExceptions(env); if (!contains_field) { env->DeleteLocalRef(field_path); return FieldValue(); } else { jobject stb_enum = ServerTimestampBehaviorInternal::ToJavaObject(env, stb); jobject field_value = env->CallObjectMethod( obj_, document_snapshot::GetMethodId(document_snapshot::kGet), field_path, stb_enum); CheckAndClearJniExceptions(env); env->DeleteLocalRef(field_path); FieldValue result{new FieldValueInternal{firestore_, field_value}}; env->DeleteLocalRef(field_value); return result; } } /* static */ bool DocumentSnapshotInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = document_snapshot::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void DocumentSnapshotInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); document_snapshot::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>#include "firestore/src/android/field_path_android.h" #include "app/src/util_android.h" #include "firestore/src/android/util_android.h" #if defined(__ANDROID__) #include "firestore/src/android/field_path_portable.h" #else // defined(__ANDROID__) #include "Firestore/core/src/firebase/firestore/model/field_path.h" #endif // defined(__ANDROID__) namespace firebase { namespace firestore { // clang-format off #define FIELD_PATH_METHODS(X) \ X(Of, "of", \ "([Ljava/lang/String;)Lcom/google/firebase/firestore/FieldPath;", \ firebase::util::kMethodTypeStatic), \ X(DocumentId, "documentId", \ "()Lcom/google/firebase/firestore/FieldPath;", \ firebase::util::kMethodTypeStatic) // clang-format on METHOD_LOOKUP_DECLARATION(field_path, FIELD_PATH_METHODS) METHOD_LOOKUP_DEFINITION(field_path, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/FieldPath", FIELD_PATH_METHODS) /* static */ jobject FieldPathConverter::ToJavaObject(JNIEnv* env, const FieldPath& path) { FieldPath::FieldPathInternal* internal = path.internal_; // If the path is key (i.e. __name__). if (internal->IsKeyFieldPath()) { jobject result = env->CallStaticObjectMethod( field_path::GetClass(), field_path::GetMethodId(field_path::kDocumentId)); CheckAndClearJniExceptions(env); return result; } // Prepare call arguments. jsize size = static_cast<jsize>(internal->size()); jobjectArray args = env->NewObjectArray(size, firebase::util::string::GetClass(), /*initialElement=*/nullptr); for (jsize i = 0; i < size; ++i) { jobject segment = env->NewStringUTF((*internal)[i].c_str()); env->SetObjectArrayElement(args, i, segment); env->DeleteLocalRef(segment); CheckAndClearJniExceptions(env); } // Make JNI call and check for error. jobject result = env->CallStaticObjectMethod( field_path::GetClass(), field_path::GetMethodId(field_path::kOf), args); CheckAndClearJniExceptions(env); env->DeleteLocalRef(args); return result; } /* static */ bool FieldPathConverter::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = field_path::CacheMethodIds(env, activity); firebase::util::CheckAndClearJniExceptions(env); return result; } /* static */ void FieldPathConverter::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); field_path::ReleaseClass(env); firebase::util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep># Copyright 2019 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # CMake file for the firebase_instance_id_desktop_impl library cmake_minimum_required (VERSION 3.1) set (CMAKE_CXX_STANDARD 11) project(firebase_instance_id_desktop_impl NONE) enable_language(C) enable_language(CXX) # Build the iid_data_generated.h header from the flatbuffer schema file. set(FLATBUFFERS_FLATC_SCHEMA_EXTRA_ARGS "--no-union-value-namespacing" "--gen-object-api" "--cpp-ptr-type" "firebase::UniquePtr") build_flatbuffers("${CMAKE_CURRENT_LIST_DIR}/iid_data.fbs" "" "iid_data_generated_includes" "${FIREBASE_FLATBUFFERS_DEPENDENCIES}" "${FIREBASE_GEN_FILE_DIR}/app/instance_id" "" "") set(iid_impl_SRCS instance_id_desktop_impl.cc instance_id_desktop_impl.h ${FIREBASE_GEN_FILE_DIR}/app/instance_id/iid_data_generated.h) add_library(firebase_instance_id_desktop_impl STATIC ${iid_impl_SRCS}) target_include_directories(firebase_instance_id_desktop_impl PUBLIC ${FIREBASE_CPP_SDK_ROOT_DIR} ${FIREBASE_GEN_FILE_DIR} ) target_link_libraries(firebase_instance_id_desktop_impl PUBLIC firebase_app PRIVATE flatbuffers firebase_rest_lib ) target_compile_definitions(firebase_instance_id_desktop_impl PRIVATE -DINTERNAL_EXPERIMENTAL=1 ) cpp_pack_library(firebase_instance_id_desktop_impl "deps/app") <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_BLOB_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_BLOB_ANDROID_H_ #include <jni.h> #include "app/src/include/firebase/app.h" namespace firebase { namespace firestore { class BlobInternal { public: static jobject BlobToJavaBlob(JNIEnv* env, const uint8_t* value, size_t size); static jbyteArray JavaBlobToJbyteArray(JNIEnv* env, jobject obj); static jclass GetClass(); private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_BLOB_ANDROID_H_ <file_sep>#include "firestore/src/android/blob_android.h" #include "app/src/util_android.h" #include "firestore/src/android/util_android.h" namespace firebase { namespace firestore { // clang-format off #define BLOB_METHODS(X) \ X(Constructor, "<init>", "(Lcom/google/protobuf/ByteString;)V", \ util::kMethodTypeInstance), \ X(FromBytes, "fromBytes", "([B)Lcom/google/firebase/firestore/Blob;", \ util::kMethodTypeStatic), \ X(ToBytes, "toBytes", "()[B") // clang-format on METHOD_LOOKUP_DECLARATION(blob, BLOB_METHODS) METHOD_LOOKUP_DEFINITION(blob, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/Blob", BLOB_METHODS) /* static */ jobject BlobInternal::BlobToJavaBlob(JNIEnv* env, const uint8_t* value, size_t size) { jobject byte_array = util::ByteBufferToJavaByteArray(env, value, size); jobject result = env->CallStaticObjectMethod( blob::GetClass(), blob::GetMethodId(blob::kFromBytes), byte_array); env->DeleteLocalRef(byte_array); CheckAndClearJniExceptions(env); return result; } /* static */ jbyteArray BlobInternal::JavaBlobToJbyteArray(JNIEnv* env, jobject obj) { jbyteArray result = static_cast<jbyteArray>( env->CallObjectMethod(obj, blob::GetMethodId(blob::kToBytes))); CheckAndClearJniExceptions(env); return result; } /* static */ jclass BlobInternal::GetClass() { return blob::GetClass(); } /* static */ bool BlobInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = blob::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void BlobInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); blob::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>package com.google.firebase.firestore.internal.cpp; /** * Place-holder dummy Java class for Firestore C++ Android clients. This is currently being used to * prevent Tricorder errors since we do not have desktop support yet. */ public class Dummy {} <file_sep>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "remote_config/src/desktop/rest_nanopb_encode.h" #include "remote_config/src/desktop/rest_nanopb.h" #include "app/meta/move.h" #include "app/src/log.h" #include "remote_config/config.pb.h" #include "nanopb/pb.h" #include "nanopb/pb_encode.h" namespace firebase { namespace remote_config { namespace internal { NPB_ALIAS_DEF(NpbFetchRequest, desktop_config_ConfigFetchRequest); NPB_ALIAS_DEF(NpbPackageData, desktop_config_PackageData); NPB_ALIAS_DEF(NpbNamedValue, desktop_config_NamedValue); pb_ostream_t CreateOutputStream(std::string* destination) { pb_ostream_t stream; stream.callback = [](pb_ostream_t* stream, const uint8_t* buf, size_t count) { std::string* result = static_cast<std::string*>(stream->state); result->insert(result->end(), buf, buf + count); return true; }; stream.state = destination; stream.max_size = SIZE_MAX; stream.bytes_written = 0; // zero out errmsg so that nanopb populates it upon errors. stream.errmsg = nullptr; return stream; } pb_callback_t EncodeStringCB(const std::string& source) { pb_callback_t callback; if (source.empty()) { callback.funcs.encode = nullptr; return callback; } callback.arg = const_cast<std::string*>(&source); callback.funcs.encode = [](pb_ostream_t* stream, const pb_field_t* field, void* const* arg) { auto& str = *static_cast<const std::string*>(*arg); if (!pb_encode_tag_for_field(stream, field)) { return false; } return pb_encode_string( stream, reinterpret_cast<const pb_byte_t*>(str.c_str()), str.size()); }; return callback; } pb_callback_t EncodeNamedValuesCB(const NamedValues& source) { pb_callback_t callback; if (source.empty()) { callback.funcs.encode = nullptr; return callback; } callback.arg = const_cast<NamedValues*>(&source); callback.funcs.encode = [](pb_ostream_t* stream, const pb_field_t* field, void* const* arg) { auto& source = *static_cast<const NamedValues*>(*arg); for (auto named_value : source) { NpbNamedValue npb_named_value = kDefaultNpbNamedValue; npb_named_value.name = EncodeStringCB(named_value.first); npb_named_value.value = EncodeStringCB(named_value.second); if (!pb_encode_tag_for_field(stream, field)) { return false; } if (!pb_encode_submessage(stream, kNpbNamedValueFields, &npb_named_value)) { return false; } } return true; }; return callback; } pb_callback_t EncodePackageDataCB(const PackageData& source) { pb_callback_t callback; callback.arg = const_cast<PackageData*>(&source); callback.funcs.encode = [](pb_ostream_t* stream, const pb_field_t* field, void* const* arg) { // Note: we can't use lambda capture here, which would be nice, because the // nanopb function pointer is a c-style function pointer, not std::function. auto& source = *static_cast<const PackageData*>(*arg); NpbPackageData npb_package = kDefaultNpbPackageData; // Ordering by type rather than struct placement. npb_package.package_name = EncodeStringCB(source.package_name); npb_package.gmp_project_id = EncodeStringCB(source.gmp_project_id); npb_package.namespace_digest = EncodeNamedValuesCB(source.namespace_digest); npb_package.custom_variable = EncodeNamedValuesCB(source.custom_variable); npb_package.app_instance_id = EncodeStringCB(source.app_instance_id); npb_package.app_instance_id_token = EncodeStringCB(source.app_instance_id_token); npb_package.sdk_version = source.sdk_version; npb_package.has_sdk_version = (source.sdk_version != 0); npb_package.requested_cache_expiration_seconds = source.requested_cache_expiration_seconds; npb_package.has_requested_cache_expiration_seconds = (source.requested_cache_expiration_seconds != 0); npb_package.fetched_config_age_seconds = source.fetched_config_age_seconds; npb_package.has_fetched_config_age_seconds = (source.fetched_config_age_seconds != -1); npb_package.active_config_age_seconds = source.active_config_age_seconds; npb_package.has_active_config_age_seconds = (source.active_config_age_seconds != -1); if (!pb_encode_tag_for_field(stream, field)) { return false; } return pb_encode_submessage(stream, kNpbPackageDataFields, &npb_package); }; return callback; } std::string EncodeFetchRequest(const ConfigFetchRequest& config_fetch_request) { std::string output; pb_ostream_t stream = CreateOutputStream(&output); NpbFetchRequest npb_request = kDefaultNpbFetchRequest; npb_request.client_version = config_fetch_request.client_version; npb_request.has_client_version = config_fetch_request.client_version != 0; npb_request.device_type = config_fetch_request.device_type; npb_request.has_device_type = config_fetch_request.device_type != 0; npb_request.device_subtype = config_fetch_request.device_subtype; npb_request.has_device_subtype = config_fetch_request.device_subtype != 0; npb_request.package_data = EncodePackageDataCB(config_fetch_request.package_data); if (!pb_encode(&stream, kNpbFetchRequestFields, &npb_request)) { LogError(stream.errmsg); } return Move(output); } } // namespace internal } // namespace remote_config } // namespace firebase <file_sep>#!/bin/bash # Runs the presubmit tests that must be run locally, because they don't work in # TAP or Guitar at the moment (see b/135205911). Execute this script before # submitting. # LINT.IfChange blaze test --config=android_arm //firebase/firestore/client/cpp:kokoro_build_test && \ blaze test --config=darwin_x86_64 //firebase/firestore/client/cpp:kokoro_build_test && \ blaze test //firebase/firestore/client/cpp:kokoro_build_test && \ blaze test --config=msvc //firebase/firestore/client/cpp:kokoro_build_test # LINT.ThenChange(//depot_firebase_cpp/firestore/client/cpp/METADATA) <file_sep>// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "instance_id/src/android/instance_id_internal.h" #include <assert.h> #include <jni.h> #include "app/memory/shared_ptr.h" #include "app/src/mutex.h" namespace firebase { namespace instance_id { namespace internal { const char* InstanceIdInternal::kCancelledError = "Cancelled"; InstanceIdInternal::InstanceIdInternal() : instance_id_(nullptr), java_instance_id_(nullptr) {} InstanceIdInternal::~InstanceIdInternal() { CancelOperations(); Initialize(instance_id_, nullptr); } void InstanceIdInternal::Initialize(InstanceId* instance_id, jobject java_instance_id) { instance_id_ = instance_id; JNIEnv* env = instance_id_->app().GetJNIEnv(); if (java_instance_id_) env->DeleteGlobalRef(java_instance_id_); java_instance_id_ = env->NewGlobalRef(java_instance_id); env->DeleteLocalRef(java_instance_id); } // Store a reference to a scheduled operation. SharedPtr<AsyncOperation> InstanceIdInternal::AddOperation( AsyncOperation* operation) { MutexLock lock(operations_mutex_); operations_.push_back(SharedPtr<AsyncOperation>(operation)); return operations_[operations_.size() - 1]; } // Remove a reference to a schedule operation. void InstanceIdInternal::RemoveOperation( const SharedPtr<AsyncOperation>& operation) { MutexLock lock(operations_mutex_); for (auto it = operations_.begin(); it != operations_.end(); ++it) { if (&(**it) == &(*operation)) { operations_.erase(it); break; } } } // Find the SharedPtr to the operation using raw pointer. SharedPtr<AsyncOperation> InstanceIdInternal::GetOperationSharedPtr( AsyncOperation* operation) { MutexLock lock(operations_mutex_); for (auto it = operations_.begin(); it != operations_.end(); ++it) { if (&(**it) == operation) { return *it; } } return SharedPtr<AsyncOperation>(); } // Cancel all scheduled operations. void InstanceIdInternal::CancelOperations() { while (true) { SharedPtr<AsyncOperation> operation_ptr; { MutexLock lock(operations_mutex_); if (operations_.empty()) { break; } operation_ptr = operations_[0]; } if (operation_ptr) { operation_ptr->Cancel(); } } } void InstanceIdInternal::CompleteOperation( const SharedPtr<AsyncOperation>& operation, Error error, const char* error_message) { future_api().Complete(operation->future_handle<void>(), error, error_message ? error_message : ""); RemoveOperation(operation); } void InstanceIdInternal::Canceled(void* function_data) { AsyncOperation* ptr = static_cast<AsyncOperation*>(function_data); // Hold a reference to AsyncOperation so that it will not be deleted during // this callback. SharedPtr<AsyncOperation> operation = ptr->instance_id_internal()->GetOperationSharedPtr(ptr); if (!operation) return; operation->instance_id_internal()->CancelOperation(operation); } } // namespace internal } // namespace instance_id } // namespace firebase <file_sep>#include "firestore/src/android/direction_android.h" namespace firebase { namespace firestore { // clang-format off #define DIRECTION_METHODS(X) \ X(Name, "name", "()Ljava/lang/String;") #define DIRECTION_FIELDS(X) \ X(Ascending, "ASCENDING", \ "Lcom/google/firebase/firestore/Query$Direction;", \ util::kFieldTypeStatic), \ X(Descending, "DESCENDING", \ "Lcom/google/firebase/firestore/Query$Direction;", \ util::kFieldTypeStatic) // clang-format on METHOD_LOOKUP_DECLARATION(direction, DIRECTION_METHODS, DIRECTION_FIELDS) METHOD_LOOKUP_DEFINITION(direction, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/Query$Direction", DIRECTION_METHODS, DIRECTION_FIELDS) jobject DirectionInternal::ascending_ = nullptr; jobject DirectionInternal::descending_ = nullptr; /* static */ jobject DirectionInternal::ToJavaObject(JNIEnv* env, Query::Direction direction) { if (direction == Query::Direction::kAscending) { return ascending_; } else { return descending_; } } /* static */ bool DirectionInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = direction::CacheMethodIds(env, activity) && direction::CacheFieldIds(env, activity); util::CheckAndClearJniExceptions(env); // Cache Java enum values. jobject value = env->GetStaticObjectField( direction::GetClass(), direction::GetFieldId(direction::kAscending)); ascending_ = env->NewGlobalRef(value); env->DeleteLocalRef(value); value = env->GetStaticObjectField( direction::GetClass(), direction::GetFieldId(direction::kDescending)); descending_ = env->NewGlobalRef(value); env->DeleteLocalRef(value); util::CheckAndClearJniExceptions(env); return result; } /* static */ void DirectionInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); direction::ReleaseClass(env); util::CheckAndClearJniExceptions(env); // Uncache Java enum values. env->DeleteGlobalRef(ascending_); ascending_ = nullptr; env->DeleteGlobalRef(descending_); descending_ = nullptr; } } // namespace firestore } // namespace firebase <file_sep># Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. include(ExternalProject) if(TARGET firestore) return() endif() # Pin to the first revision that includes these changes: # https://github.com/firebase/firebase-ios-sdk/pull/4984 # https://github.com/firebase/firebase-ios-sdk/pull/5027 # # These changes are required for the firebase-ios-sdk build to interoperate # well with a wrapper build. Once M67 iOS releases this should point to the # Firestore release tag. set(version fb0fc07609a55cd2e5acf47fe034bf0c8e8419ad) ExternalProject_Add( firestore DOWNLOAD_DIR ${FIREBASE_DOWNLOAD_DIR} DOWNLOAD_NAME firestore-${version}.tar.gz URL https://github.com/firebase/firebase-ios-sdk/archive/${version}.tar.gz PREFIX ${PROJECT_BINARY_DIR} CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND "" TEST_COMMAND "" ) <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_LAMBDA_EVENT_LISTENER_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_LAMBDA_EVENT_LISTENER_H_ #include "app/meta/move.h" #include "firestore/src/include/firebase/firestore/event_listener.h" #include "firebase/firestore/firestore_errors.h" #if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) #include <functional> namespace firebase { namespace firestore { /** * A particular EventListener type that wraps a listener provided by user in the * form of lambda. */ template <typename T> class LambdaEventListener : public EventListener<T> { public: LambdaEventListener(std::function<void(const T&, Error)> callback) : callback_(firebase::Move(callback)) { FIREBASE_ASSERT(callback); } void OnEvent(const T& value, Error error) override { callback_(value, error); } private: std::function<void(const T&, Error)> callback_; }; template <> class LambdaEventListener<void> : public EventListener<void> { public: LambdaEventListener(std::function<void()> callback) : callback_(firebase::Move(callback)) { FIREBASE_ASSERT(callback); } void OnEvent(Error) override { callback_(); } private: std::function<void()> callback_; }; } // namespace firestore } // namespace firebase #endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_LAMBDA_EVENT_LISTENER_H_ <file_sep>// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef FIREBASE_INSTANCE_ID_CLIENT_CPP_SRC_INCLUDE_FIREBASE_INSTANCE_ID_H_ #define FIREBASE_INSTANCE_ID_CLIENT_CPP_SRC_INCLUDE_FIREBASE_INSTANCE_ID_H_ #include <cstdint> #include <string> #include "firebase/app.h" #include "firebase/future.h" #include "firebase/internal/common.h" #if !defined(DOXYGEN) && !defined(SWIG) FIREBASE_APP_REGISTER_CALLBACKS_REFERENCE(instance_id) #endif // !defined(DOXYGEN) && !defined(SWIG) /// @brief Namespace that encompasses all Firebase APIs. namespace firebase { namespace instance_id { /// InstanceId error codes. enum Error { kErrorNone = 0, /// An unknown error occurred. kErrorUnknown, /// Request could not be validated from this client. kErrorAuthentication, /// Instance ID service cannot be accessed. kErrorNoAccess, /// Request to instance ID backend timed out. kErrorTimeout, /// No network available to reach the servers. kErrorNetwork, /// A similar operation is in progress so aborting this one. kErrorOperationInProgress, /// Some of the parameters of the request were invalid. kErrorInvalidRequest, // ID is invalid and should be reset. kErrorIdInvalid, }; #if defined(INTERNAL_EXPERIMENTAL) // TODO(b/69930393): Unfortunately, the Android implementation uses a service // to notify the application of token refresh events. It's a load of work // to setup a service to forward token change events to the application so // - in order to unblock A/B testing - we'll add support later. /// @brief Can be registered by an application for notifications when an app's /// instance ID changes. class InstanceIdListener { public: InstanceIdListener(); virtual ~InstanceIdListener(); /// @brief Called when the system determines that the tokens need to be /// refreshed. The application should call GetToken and send the tokens to /// all application servers. /// /// This will not be called very frequently, it is needed for key rotation /// and to handle Instance ID changes due to: /// <ul> /// <li>App deletes Instance ID /// <li>App is restored on a new device /// <li>User uninstalls/reinstall the app /// <li>User clears app data /// </ul> /// /// The system will throttle the refresh event across all devices to /// avoid overloading application servers with token updates. virtual void onTokenRefresh() = 0; }; #endif // defined(INTERNAL_EXPERIMENTAL) #if defined(INTERNAL_EXPERIMENTAL) // Expose private members of InstanceId to the unit tests. // See FRIEND_TEST() macro in gtest.h for the naming convention here. class InstanceIdTest_TestGetTokenEntityScope_Test; class InstanceIdTest_TestDeleteTokenEntityScope_Test; #endif // defined(INTERNAL_EXPERIMENTAL) #if !defined(DOXYGEN) namespace internal { // Implementation specific data for an InstanceId. class InstanceIdInternal; } // namespace internal #endif // !defined(DOXYGEN) /// @brief Instance ID provides a unique identifier for each app instance and /// a mechanism to authenticate and authorize actions (for example, sending a /// FCM message). /// /// An Instance ID is long lived, but might be reset if the device is not used /// for a long time or the Instance ID service detects a problem. If the /// Instance ID has become invalid, the app can request a new one and send it to /// the app server. To prove ownership of Instance ID and to allow servers to /// access data or services associated with the app, call GetToken. /// /// @if INTERNAL_EXPERIMENTAL /// If an Instance ID is reset, the app will be notified via InstanceIdListener. /// @endif class InstanceId { public: ~InstanceId(); /// @brief Gets the App this object is connected to. /// /// @returns App this object is connected to. App& app() const { return *app_; } #if defined(INTERNAL_EXPERIMENTAL) // TODO(b/69932424): Blocked by iOS implementation. /// @brief Get the time the instance ID was created. /// /// @returns Time (in milliseconds since the epoch) when the instance ID was /// created. int64_t creation_time() const; #endif // defined(INTERNAL_EXPERIMENTAL) /// @brief Returns a stable identifier that uniquely identifies the app /// instance. /// /// @returns Unique identifier for the app instance. Future<std::string> GetId() const; /// @brief Get the results of the most recent call to @ref GetId. Future<std::string> GetIdLastResult() const; /// @brief Delete the ID associated with the app, revoke all tokens and /// allocate a new ID. Future<void> DeleteId(); /// @brief Get the results of the most recent call to @ref DeleteId. Future<void> DeleteIdLastResult() const; /// @brief Returns a token that authorizes an Entity to perform an action on /// behalf of the application identified by Instance ID. /// /// This is similar to an OAuth2 token except, it applies to the /// application instance instead of a user. /// /// For example, to get a token that can be used to send messages to an /// application via Firebase Messaging, set entity to the /// sender ID, and set scope to "FCM". /// /// @returns A token that can identify and authorize the instance of the /// application on the device. Future<std::string> GetToken(); /// @brief Get the results of the most recent call to @ref GetToken. Future<std::string> GetTokenLastResult() const; /// @brief Revokes access to a scope (action) Future<void> DeleteToken(); /// @brief Get the results of the most recent call to @ref DeleteToken. Future<void> DeleteTokenLastResult() const; /// @brief Returns the InstanceId object for an App creating the InstanceId /// if required. /// /// @param[in] app The App to create an InstanceId object from. /// On <b>iOS</b> this must be the default Firebase App. /// @param[out] init_result_out Optional: If provided, write the init result /// here. Will be set to kInitResultSuccess if initialization succeeded, or /// kInitResultFailedMissingDependency on Android if Google Play services is /// not available on the current device. /// /// @returns InstanceId object if successful, nullptr otherwise. static InstanceId* GetInstanceId(App* app, InitResult* init_result_out = nullptr); #if defined(INTERNAL_EXPERIMENTAL) // TODO(b/69930393): Needs to be implemented on Android. /// @brief Set a listener for instance ID changes. /// /// @param listener Listener which is notified when instance ID changes. /// /// @returns Previously registered listener. static InstanceIdListener* SetListener(InstanceIdListener* listener); // Delete the instance_id_internal_. void DeleteInternal(); #endif // defined(INTERNAL_EXPERIMENTAL) private: InstanceId(App* app, internal::InstanceIdInternal* instance_id_internal); #if defined(INTERNAL_EXPERIMENTAL) // Can access GetToken() and DeleteToken() methods for testing. friend class InstanceIdTest_TestGetTokenEntityScope_Test; friend class InstanceIdTest_TestDeleteTokenEntityScope_Test; /// @brief Returns a token that authorizes an Entity to perform an action on /// behalf of the application identified by Instance ID. /// /// This is similar to an OAuth2 token except, it applies to the /// application instance instead of a user. /// /// For example, to get a token that can be used to send messages to an /// application via Firebase Messaging, set entity to the /// sender ID, and set scope to "FCM". /// /// @param entity Entity authorized by the token. /// @param scope Action authorized for entity. /// /// @returns A token that can identify and authorize the instance of the /// application on the device. Future<std::string> GetToken(const char* entity, const char* scope); /// @brief Revokes access to a scope (action) /// /// @param entity entity Entity that must no longer have access. /// @param scope Action that entity is no longer authorized to perform. Future<void> DeleteToken(const char* entity, const char* scope); #endif // defined(INTERNAL_EXPERIMENTAL) private: App* app_; internal::InstanceIdInternal* instance_id_internal_; }; } // namespace instance_id } // namespace firebase #endif // FIREBASE_INSTANCE_ID_CLIENT_CPP_SRC_INCLUDE_FIREBASE_INSTANCE_ID_H_ <file_sep>// Copyright 2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef FIREBASE_REMOTE_CONFIG_CLIENT_CPP_SRC_COMMON_H_ #define FIREBASE_REMOTE_CONFIG_CLIENT_CPP_SRC_COMMON_H_ #include "app/src/reference_counted_future_impl.h" namespace firebase { namespace remote_config { enum RemoteConfigFn { kRemoteConfigFnFetch, kRemoteConfigFnEnsureInitialized, kRemoteConfigFnActivate, kRemoteConfigFnFetchAndActivate, kRemoteConfigFnSetDefaults, kRemoteConfigFnSetConfigSettings, kRemoteConfigFnCount }; /// @brief Describes the error codes returned by futures. enum FutureStatus { // The future returned successfully. // This should always evaluate to zero, to ensure that the future returns // a zero result on success. kFutureStatusSuccess = 0, // The future returned unsuccessfully. Check GetInfo() for further details. kFutureStatusFailure, }; // Data structure which holds the Future API implementation with the only // future required by this API (fetch_future_). class FutureData { public: FutureData() : api_(kRemoteConfigFnCount) {} ~FutureData() {} ReferenceCountedFutureImpl* api() { return &api_; } // Create FutureData singleton. static FutureData* Create(); // Destroy the FutureData singleton. static void Destroy(); // Get the Future data singleton. static FutureData* Get(); private: ReferenceCountedFutureImpl api_; static FutureData *s_future_data_; }; namespace internal { // Determines whether remote config is initialized. // Implemented in each platform module. bool IsInitialized(); // Registers a cleanup task for this module if auto-initialization is disabled. void RegisterTerminateOnDefaultAppDestroy(); // Remove the cleanup task for this module if auto-initialization is disabled. void UnregisterTerminateOnDefaultAppDestroy(); } // namespace internal } // namespace remote_config } // namespace firebase #endif // FIREBASE_REMOTE_CONFIG_CLIENT_CPP_SRC_COMMON_H_ <file_sep>#include "firestore/src/android/metadata_changes_android.h" namespace firebase { namespace firestore { // clang-format off #define METADATA_CHANGES_METHODS(X) X(Name, "name", "()Ljava/lang/String;") #define METADATA_CHANGES_FIELDS(X) \ X(Exclude, "EXCLUDE", "Lcom/google/firebase/firestore/MetadataChanges;", \ util::kFieldTypeStatic), \ X(Include, "INCLUDE", "Lcom/google/firebase/firestore/MetadataChanges;", \ util::kFieldTypeStatic) // clang-format on METHOD_LOOKUP_DECLARATION(metadata_changes, METADATA_CHANGES_METHODS, METADATA_CHANGES_FIELDS) METHOD_LOOKUP_DEFINITION(metadata_changes, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/MetadataChanges", METADATA_CHANGES_METHODS, METADATA_CHANGES_FIELDS) jobject MetadataChangesInternal::exclude_ = nullptr; jobject MetadataChangesInternal::include_ = nullptr; /* static */ jobject MetadataChangesInternal::ToJavaObject( JNIEnv* env, MetadataChanges metadata_changes) { if (metadata_changes == MetadataChanges::kExclude) { return exclude_; } else { return include_; } } /* static */ bool MetadataChangesInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = metadata_changes::CacheMethodIds(env, activity) && metadata_changes::CacheFieldIds(env, activity); util::CheckAndClearJniExceptions(env); // Cache Java enum values. jobject value = env->GetStaticObjectField( metadata_changes::GetClass(), metadata_changes::GetFieldId(metadata_changes::kExclude)); exclude_ = env->NewGlobalRef(value); env->DeleteLocalRef(value); value = env->GetStaticObjectField( metadata_changes::GetClass(), metadata_changes::GetFieldId(metadata_changes::kInclude)); include_ = env->NewGlobalRef(value); env->DeleteLocalRef(value); return result; } /* static */ void MetadataChangesInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); metadata_changes::ReleaseClass(env); util::CheckAndClearJniExceptions(env); // Uncache Java enum values. env->DeleteGlobalRef(exclude_); exclude_ = nullptr; env->DeleteGlobalRef(include_); include_ = nullptr; } } // namespace firestore } // namespace firebase <file_sep>#include "firestore/src/android/document_reference_android.h" #include "app/meta/move.h" #include "app/src/assert.h" #include "app/src/util_android.h" #include "firestore/src/android/collection_reference_android.h" #include "firestore/src/android/event_listener_android.h" #include "firestore/src/android/field_path_android.h" #include "firestore/src/android/field_value_android.h" #include "firestore/src/android/lambda_event_listener.h" #include "firestore/src/android/listener_registration_android.h" #include "firestore/src/android/metadata_changes_android.h" #include "firestore/src/android/promise_android.h" #include "firestore/src/android/set_options_android.h" #include "firestore/src/android/source_android.h" #include "firestore/src/android/util_android.h" #include "firestore/src/include/firebase/firestore.h" namespace firebase { namespace firestore { // clang-format off #define DOCUMENT_REFERENCE_METHODS(X) \ X(GetId, "getId", "()Ljava/lang/String;"), \ X(GetPath, "getPath", "()Ljava/lang/String;"), \ X(GetParent, "getParent", \ "()Lcom/google/firebase/firestore/CollectionReference;"), \ X(Collection, "collection", "(Ljava/lang/String;)" \ "Lcom/google/firebase/firestore/CollectionReference;"), \ X(Get, "get", \ "(Lcom/google/firebase/firestore/Source;)" \ "Lcom/google/android/gms/tasks/Task;"), \ X(Set, "set", \ "(Ljava/lang/Object;Lcom/google/firebase/firestore/SetOptions;)" \ "Lcom/google/android/gms/tasks/Task;"), \ X(Update, "update", \ "(Ljava/util/Map;)Lcom/google/android/gms/tasks/Task;"), \ X(UpdateVarargs, "update", \ "(Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;" \ "[Ljava/lang/Object;)Lcom/google/android/gms/tasks/Task;"), \ X(Delete, "delete", "()Lcom/google/android/gms/tasks/Task;"), \ X(AddSnapshotListener, "addSnapshotListener", \ "(Lcom/google/firebase/firestore/MetadataChanges;" \ "Lcom/google/firebase/firestore/EventListener;)" \ "Lcom/google/firebase/firestore/ListenerRegistration;") // clang-format on METHOD_LOOKUP_DECLARATION(document_reference, DOCUMENT_REFERENCE_METHODS) METHOD_LOOKUP_DEFINITION(document_reference, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/DocumentReference", DOCUMENT_REFERENCE_METHODS) Firestore* DocumentReferenceInternal::firestore() { FIREBASE_ASSERT(firestore_->firestore_public() != nullptr); return firestore_->firestore_public(); } const std::string& DocumentReferenceInternal::id() const { if (!cached_id_.empty()) { return cached_id_; } JNIEnv* env = firestore_->app()->GetJNIEnv(); jstring id = static_cast<jstring>(env->CallObjectMethod( obj_, document_reference::GetMethodId(document_reference::kGetId))); cached_id_ = util::JniStringToString(env, id); CheckAndClearJniExceptions(env); return cached_id_; } const std::string& DocumentReferenceInternal::path() const { if (!cached_path_.empty()) { return cached_path_; } JNIEnv* env = firestore_->app()->GetJNIEnv(); jstring path = static_cast<jstring>(env->CallObjectMethod( obj_, document_reference::GetMethodId(document_reference::kGetPath))); cached_path_ = util::JniStringToString(env, path); CheckAndClearJniExceptions(env); return cached_path_; } CollectionReference DocumentReferenceInternal::Parent() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject parent = env->CallObjectMethod( obj_, document_reference::GetMethodId(document_reference::kGetParent)); CollectionReferenceInternal* internal = new CollectionReferenceInternal{firestore_, parent}; env->DeleteLocalRef(parent); CheckAndClearJniExceptions(env); return CollectionReference(internal); } CollectionReference DocumentReferenceInternal::Collection( const std::string& collection_path) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jstring path_string = env->NewStringUTF(collection_path.c_str()); jobject collection = env->CallObjectMethod( obj_, document_reference::GetMethodId(document_reference::kCollection), path_string); env->DeleteLocalRef(path_string); CheckAndClearJniExceptions(env); CollectionReferenceInternal* internal = new CollectionReferenceInternal{firestore_, collection}; env->DeleteLocalRef(collection); CheckAndClearJniExceptions(env); return CollectionReference(internal); } Future<DocumentSnapshot> DocumentReferenceInternal::Get(Source source) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject task = env->CallObjectMethod( obj_, document_reference::GetMethodId(document_reference::kGet), SourceInternal::ToJavaObject(env, source)); CheckAndClearJniExceptions(env); auto promise = MakePromise<DocumentSnapshot, DocumentSnapshotInternal>(); promise.RegisterForTask(DocumentReferenceFn::kGet, task); env->DeleteLocalRef(task); CheckAndClearJniExceptions(env); return promise.GetFuture(); } Future<DocumentSnapshot> DocumentReferenceInternal::GetLastResult() { return LastResult<DocumentSnapshot>(DocumentReferenceFn::kGet); } Future<void> DocumentReferenceInternal::Set(const MapFieldValue& data, const SetOptions& options) { FieldValueInternal map_value(data); JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject java_options = SetOptionsInternal::ToJavaObject(env, options); CheckAndClearJniExceptions(env); jobject task = env->CallObjectMethod( obj_, document_reference::GetMethodId(document_reference::kSet), map_value.java_object(), java_options); env->DeleteLocalRef(java_options); CheckAndClearJniExceptions(env); auto promise = MakePromise<void, void>(); promise.RegisterForTask(DocumentReferenceFn::kSet, task); env->DeleteLocalRef(task); CheckAndClearJniExceptions(env); return promise.GetFuture(); } Future<void> DocumentReferenceInternal::SetLastResult() { return LastResult<void>(DocumentReferenceFn::kSet); } Future<void> DocumentReferenceInternal::Update(const MapFieldValue& data) { FieldValueInternal map_value(data); JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject task = env->CallObjectMethod( obj_, document_reference::GetMethodId(document_reference::kUpdate), map_value.java_object()); CheckAndClearJniExceptions(env); auto promise = MakePromise<void, void>(); promise.RegisterForTask(DocumentReferenceFn::kUpdate, task); env->DeleteLocalRef(task); CheckAndClearJniExceptions(env); return promise.GetFuture(); } Future<void> DocumentReferenceInternal::Update(const MapFieldPathValue& data) { if (data.empty()) { return Update(MapFieldValue{}); } JNIEnv* env = firestore_->app()->GetJNIEnv(); auto iter = data.begin(); jobject first_field = FieldPathConverter::ToJavaObject(env, iter->first); jobject first_value = iter->second.internal_->java_object(); ++iter; // Make the varargs jobjectArray more_fields_and_values = MapFieldPathValueToJavaArray(firestore_, iter, data.end()); jobject task = env->CallObjectMethod( obj_, document_reference::GetMethodId(document_reference::kUpdateVarargs), first_field, first_value, more_fields_and_values); env->DeleteLocalRef(first_field); env->DeleteLocalRef(more_fields_and_values); CheckAndClearJniExceptions(env); auto promise = MakePromise<void, void>(); promise.RegisterForTask(DocumentReferenceFn::kUpdate, task); env->DeleteLocalRef(task); CheckAndClearJniExceptions(env); return promise.GetFuture(); } Future<void> DocumentReferenceInternal::UpdateLastResult() { return LastResult<void>(DocumentReferenceFn::kUpdate); } Future<void> DocumentReferenceInternal::Delete() { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject task = env->CallObjectMethod( obj_, document_reference::GetMethodId(document_reference::kDelete)); CheckAndClearJniExceptions(env); auto promise = MakePromise<void, void>(); promise.RegisterForTask(DocumentReferenceFn::kDelete, task); env->DeleteLocalRef(task); CheckAndClearJniExceptions(env); return promise.GetFuture(); } Future<void> DocumentReferenceInternal::DeleteLastResult() { return LastResult<void>(DocumentReferenceFn::kDelete); } #if defined(FIREBASE_USE_STD_FUNCTION) ListenerRegistration DocumentReferenceInternal::AddSnapshotListener( MetadataChanges metadata_changes, std::function<void(const DocumentSnapshot&, Error)> callback) { LambdaEventListener<DocumentSnapshot>* listener = new LambdaEventListener<DocumentSnapshot>(firebase::Move(callback)); return AddSnapshotListener(metadata_changes, listener, /*passing_listener_ownership=*/true); } #endif // defined(FIREBASE_USE_STD_FUNCTION) ListenerRegistration DocumentReferenceInternal::AddSnapshotListener( MetadataChanges metadata_changes, EventListener<DocumentSnapshot>* listener, bool passing_listener_ownership) { JNIEnv* env = firestore_->app()->GetJNIEnv(); // Create listener. jobject java_listener = EventListenerInternal::EventListenerToJavaEventListener(env, firestore_, listener); jobject java_metadata = MetadataChangesInternal::ToJavaObject(env, metadata_changes); // Register listener. jobject java_registration = env->CallObjectMethod( obj_, document_reference::GetMethodId(document_reference::kAddSnapshotListener), java_metadata, java_listener); env->DeleteLocalRef(java_listener); CheckAndClearJniExceptions(env); // Wrapping ListenerRegistrationInternal* registration = new ListenerRegistrationInternal{ firestore_, listener, passing_listener_ownership, java_registration}; env->DeleteLocalRef(java_registration); return ListenerRegistration{registration}; } /* static */ jclass DocumentReferenceInternal::GetClass() { return document_reference::GetClass(); } /* static */ bool DocumentReferenceInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = document_reference::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void DocumentReferenceInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); document_reference::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>#include "firestore/src/android/document_change_type_android.h" #include "app/src/util_android.h" namespace firebase { namespace firestore { using Type = DocumentChange::Type; // clang-format off #define DOCUMENT_CHANGE_TYPE_METHODS(X) X(Name, "name", "()Ljava/lang/String;") #define DOCUMENT_CHANGE_TYPE_FIELDS(X) \ X(Added, "ADDED", "Lcom/google/firebase/firestore/DocumentChange$Type;", \ util::kFieldTypeStatic), \ X(Modified, "MODIFIED", \ "Lcom/google/firebase/firestore/DocumentChange$Type;", \ util::kFieldTypeStatic), \ X(Removed, "REMOVED", "Lcom/google/firebase/firestore/DocumentChange$Type;", \ util::kFieldTypeStatic) // clang-format on METHOD_LOOKUP_DECLARATION(document_change_type, DOCUMENT_CHANGE_TYPE_METHODS, DOCUMENT_CHANGE_TYPE_FIELDS) METHOD_LOOKUP_DEFINITION(document_change_type, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/DocumentChange$Type", DOCUMENT_CHANGE_TYPE_METHODS, DOCUMENT_CHANGE_TYPE_FIELDS) std::map<Type, jobject>* DocumentChangeTypeInternal::cpp_enum_to_java_ = nullptr; /* static */ Type DocumentChangeTypeInternal::JavaDocumentChangeTypeToDocumentChangeType( JNIEnv* env, jobject type) { for (const auto& kv : *cpp_enum_to_java_) { if (env->IsSameObject(type, kv.second)) { return kv.first; } } FIREBASE_ASSERT_MESSAGE(false, "Unknown DocumentChange type."); return Type::kAdded; } /* static */ bool DocumentChangeTypeInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = document_change_type::CacheMethodIds(env, activity) && document_change_type::CacheFieldIds(env, activity); util::CheckAndClearJniExceptions(env); // Cache Java enum values. cpp_enum_to_java_ = new std::map<Type, jobject>(); const auto add_enum = [env](Type type, document_change_type::Field field) { jobject value = env->GetStaticObjectField(document_change_type::GetClass(), document_change_type::GetFieldId(field)); (*cpp_enum_to_java_)[type] = env->NewGlobalRef(value); env->DeleteLocalRef(value); util::CheckAndClearJniExceptions(env); }; add_enum(Type::kAdded, document_change_type::kAdded); add_enum(Type::kModified, document_change_type::kModified); add_enum(Type::kRemoved, document_change_type::kRemoved); return result; } /* static */ void DocumentChangeTypeInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); document_change_type::ReleaseClass(env); util::CheckAndClearJniExceptions(env); // Uncache Java enum values. for (auto& kv : *cpp_enum_to_java_) { env->DeleteGlobalRef(kv.second); } util::CheckAndClearJniExceptions(env); delete cpp_enum_to_java_; cpp_enum_to_java_ = nullptr; } } // namespace firestore } // namespace firebase <file_sep>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "database/src/desktop/persistence/file_io.h" #include <fstream> #include <iostream> #include "flatbuffers/util.h" namespace firebase { namespace database { namespace internal { FileIoInterface::~FileIoInterface() {} FileIo::~FileIo() {} bool FileIo::ClearFile(const char* name) { std::ofstream ofs(name, std::ios::binary); if (!ofs.is_open()) return false; ofs.write(nullptr, 0); return !ofs.bad(); } bool FileIo::AppendToFile(const char* name, const char* buffer, size_t size) { std::ofstream ofs(name, std::ios::binary | std::ios::app); if (!ofs.is_open()) return false; ofs.write(buffer, size); return !ofs.bad(); } bool FileIo::ReadFromFile(const char* name, std::string* buffer) { bool result = flatbuffers::LoadFile(name, true, buffer); return result; } bool FileIo::SetByte(const char* name, size_t offset, uint8_t byte) { std::fstream ofs(name, std::ios::binary | std::ios::in | std::ios::out); ofs.seekp(offset); ofs.put(byte); return !ofs.bad(); } } // namespace internal } // namespace database } // namespace firebase <file_sep>// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "instance_id/src/include/firebase/instance_id.h" #include <jni.h> #include <cstdint> #include <string> #include "app/memory/shared_ptr.h" #include "app/src/include/firebase/app.h" #include "app/src/include/firebase/internal/common.h" #include "app/src/util_android.h" #include "instance_id/src/android/instance_id_internal.h" namespace firebase { namespace instance_id { // clang-format off #define INSTANCE_ID_METHODS(X) \ X(GetId, "getId", "()Ljava/lang/String;"), \ X(GetCreationTime, "getCreationTime", "()J"), \ X(DeleteInstanceId, "deleteInstanceId", "()V"), \ X(GetToken, "getToken", "(Ljava/lang/String;Ljava/lang/String;)" \ "Ljava/lang/String;"), \ X(DeleteToken, "deleteToken", "(Ljava/lang/String;Ljava/lang/String;)V"), \ X(GetInstance, "getInstance", "(Lcom/google/firebase/FirebaseApp;)" \ "Lcom/google/firebase/iid/FirebaseInstanceId;", \ firebase::util::kMethodTypeStatic) // clang-format on METHOD_LOOKUP_DECLARATION(instance_id, INSTANCE_ID_METHODS) METHOD_LOOKUP_DEFINITION(instance_id, PROGUARD_KEEP_CLASS "com/google/firebase/iid/FirebaseInstanceId", INSTANCE_ID_METHODS) namespace { // Number of times this module has been initialized. static int g_initialization_count = 0; static bool Initialize(const App& app) { if (g_initialization_count) { g_initialization_count++; return true; } JNIEnv* env = app.GetJNIEnv(); if (!util::Initialize(env, app.activity())) return false; if (!instance_id::CacheMethodIds(env, app.activity())) { util::Terminate(env); return false; } g_initialization_count++; return true; } static void Terminate(const App& app) { if (!g_initialization_count) return; g_initialization_count--; if (!g_initialization_count) { JNIEnv* env = app.GetJNIEnv(); instance_id::ReleaseClass(env); util::Terminate(env); } } // Maps an error message to an error code. struct ErrorMessageToCode { const char* message; Error code; }; // The Android implemenation of IID does not raise specific exceptions which // means we can only use error strings to convert to error codes. static Error ExceptionStringToError(const char* error_message) { static const ErrorMessageToCode kErrorMessageToCodes[] = { {/* ERROR_SERVICE_NOT_AVAILABLE */ "SERVICE_NOT_AVAILABLE", kErrorNoAccess}, {/* ERROR_INSTANCE_ID_RESET */ "INSTANCE_ID_RESET", kErrorIdInvalid}, }; if (strlen(error_message)) { for (int i = 0; i < FIREBASE_ARRAYSIZE(kErrorMessageToCodes); ++i) { const auto& message_to_code = kErrorMessageToCodes[i]; if (strcmp(message_to_code.message, error_message) == 0) { return message_to_code.code; } } return kErrorUnknown; } return kErrorNone; } } // namespace using internal::AsyncOperation; using internal::InstanceIdInternal; int64_t InstanceId::creation_time() const { if (!instance_id_internal_) return 0; JNIEnv* env = app().GetJNIEnv(); return env->CallLongMethod( instance_id_internal_->java_instance_id(), instance_id::GetMethodId(instance_id::kGetCreationTime)); } Future<std::string> InstanceId::GetId() const { if (!instance_id_internal_) return Future<std::string>(); JNIEnv* env = app().GetJNIEnv(); SharedPtr<AsyncOperation> operation = instance_id_internal_->AddOperation(new AsyncOperation( env, instance_id_internal_, instance_id_internal_ ->FutureAlloc<std::string>(InstanceIdInternal::kApiFunctionGetId) .get())); util::RunOnBackgroundThread( env, [](void* function_data) { // Assume that when this callback is called, AsyncOperation should still // be in instance_id_internal->operations_ or this callback should not // be called at all due to the lock in CppThreadDispatcherContext. AsyncOperation* op_ptr = static_cast<AsyncOperation*>(function_data); InstanceIdInternal* instance_id_internal = op_ptr->instance_id_internal(); // Hold a reference to AsyncOperation so that it will not be deleted // during this callback. SharedPtr<AsyncOperation> operation = instance_id_internal->GetOperationSharedPtr(op_ptr); if (!operation) return; JNIEnv* env = instance_id_internal->instance_id()->app().GetJNIEnv(); jobject java_instance_id = env->NewLocalRef(instance_id_internal->java_instance_id()); jmethodID java_instance_id_method = instance_id::GetMethodId(instance_id::kGetId); operation->ReleaseExecuteCancelLock(); jobject id_jstring = env->CallObjectMethod(java_instance_id, java_instance_id_method); std::string error = util::GetAndClearExceptionMessage(env); std::string id = util::JniStringToString(env, id_jstring); env->DeleteLocalRef(java_instance_id); if (operation->AcquireExecuteCancelLock()) { instance_id_internal->CompleteOperationWithResult( operation, id, ExceptionStringToError(error.c_str()), error.c_str()); } }, &(*operation), InstanceIdInternal::CanceledWithResult<std::string>, &(*operation)); return GetIdLastResult(); } Future<void> InstanceId::DeleteId() { if (!instance_id_internal_) return Future<void>(); JNIEnv* env = app().GetJNIEnv(); SharedPtr<AsyncOperation> operation = instance_id_internal_->AddOperation( new AsyncOperation(env, instance_id_internal_, instance_id_internal_ ->FutureAlloc<std::string>( InstanceIdInternal::kApiFunctionDeleteId) .get())); util::RunOnBackgroundThread( env, [](void* function_data) { // Assume that when this callback is called, AsyncOperation should still // be in instance_id_internal->operations_ or this callback should not // be called at all due to the lock in CppThreadDispatcherContext. AsyncOperation* op_ptr = static_cast<AsyncOperation*>(function_data); InstanceIdInternal* instance_id_internal = op_ptr->instance_id_internal(); // Hold a reference to AsyncOperation so that it will not be deleted // during this callback. SharedPtr<AsyncOperation> operation = instance_id_internal->GetOperationSharedPtr(op_ptr); if (!operation) return; JNIEnv* env = instance_id_internal->instance_id()->app().GetJNIEnv(); jobject java_instance_id = env->NewLocalRef(instance_id_internal->java_instance_id()); jmethodID java_instance_id_method = instance_id::GetMethodId(instance_id::kDeleteInstanceId); operation->ReleaseExecuteCancelLock(); env->CallVoidMethod(java_instance_id, java_instance_id_method); std::string error = util::GetAndClearExceptionMessage(env); env->DeleteLocalRef(java_instance_id); if (operation->AcquireExecuteCancelLock()) { instance_id_internal->CompleteOperation( operation, ExceptionStringToError(error.c_str()), error.c_str()); } }, &(*operation), InstanceIdInternal::Canceled, &(*operation)); return DeleteIdLastResult(); } // Context for a token retrieve / delete operation. class AsyncTokenOperation : public AsyncOperation { public: AsyncTokenOperation(JNIEnv* env, InstanceIdInternal* instance_id_internal, FutureHandle future_handle, const char* entity, const char* scope) : AsyncOperation(env, instance_id_internal, future_handle), entity_(entity), scope_(scope) { derived_ = this; } virtual ~AsyncTokenOperation() {} const std::string& entity() const { return entity_; } const std::string& scope() const { return scope_; } private: std::string entity_; std::string scope_; }; Future<std::string> InstanceId::GetToken(const char* entity, const char* scope) { if (!instance_id_internal_) return Future<std::string>(); JNIEnv* env = app().GetJNIEnv(); SharedPtr<AsyncOperation> operation = instance_id_internal_->AddOperation( new AsyncTokenOperation(env, instance_id_internal_, instance_id_internal_ ->FutureAlloc<std::string>( InstanceIdInternal::kApiFunctionGetToken) .get(), entity, scope)); util::RunOnBackgroundThread( env, [](void* function_data) { // Assume that when this callback is called, AsyncOperation should still // be in instance_id_internal->operations_ or this callback should not // be called at all due to the lock in CppThreadDispatcherContext. AsyncTokenOperation* op_ptr = static_cast<AsyncTokenOperation*>(function_data); InstanceIdInternal* instance_id_internal = op_ptr->instance_id_internal(); // Hold a reference to AsyncOperation so that it will not be deleted // during this callback. SharedPtr<AsyncOperation> operation = instance_id_internal->GetOperationSharedPtr(op_ptr); if (!operation) return; JNIEnv* env = instance_id_internal->instance_id()->app().GetJNIEnv(); jobject java_instance_id = env->NewLocalRef(instance_id_internal->java_instance_id()); jmethodID java_instance_id_method = instance_id::GetMethodId(instance_id::kGetToken); jobject entity_jstring = env->NewStringUTF(op_ptr->entity().c_str()); jobject scope_jstring = env->NewStringUTF(op_ptr->scope().c_str()); operation->ReleaseExecuteCancelLock(); jobject token_jstring = env->CallObjectMethod(java_instance_id, java_instance_id_method, entity_jstring, scope_jstring); std::string error = util::GetAndClearExceptionMessage(env); std::string token = util::JniStringToString(env, token_jstring); env->DeleteLocalRef(java_instance_id); env->DeleteLocalRef(entity_jstring); env->DeleteLocalRef(scope_jstring); if (operation->AcquireExecuteCancelLock()) { instance_id_internal->CompleteOperationWithResult( operation, token, ExceptionStringToError(error.c_str()), error.c_str()); } }, &(*operation), InstanceIdInternal::CanceledWithResult<std::string>, &(*operation)); return GetTokenLastResult(); } Future<void> InstanceId::DeleteToken(const char* entity, const char* scope) { if (!instance_id_internal_) return Future<void>(); JNIEnv* env = app().GetJNIEnv(); SharedPtr<AsyncOperation> operation = instance_id_internal_->AddOperation(new AsyncTokenOperation( env, instance_id_internal_, instance_id_internal_ ->FutureAlloc<std::string>( InstanceIdInternal::kApiFunctionDeleteToken) .get(), entity, scope)); util::RunOnBackgroundThread( env, [](void* function_data) { // Assume that when this callback is called, AsyncOperation should still // be in instance_id_internal->operations_ or this callback should not // be called at all due to the lock in CppThreadDispatcherContext. AsyncTokenOperation* op_ptr = static_cast<AsyncTokenOperation*>(function_data); InstanceIdInternal* instance_id_internal = op_ptr->instance_id_internal(); // Hold a reference to AsyncOperation so that it will not be deleted // during this callback. SharedPtr<AsyncOperation> operation = instance_id_internal->GetOperationSharedPtr(op_ptr); if (!operation) return; JNIEnv* env = instance_id_internal->instance_id()->app().GetJNIEnv(); jobject entity_jstring = env->NewStringUTF(op_ptr->entity().c_str()); jobject scope_jstring = env->NewStringUTF(op_ptr->scope().c_str()); jobject java_instance_id = env->NewLocalRef(instance_id_internal->java_instance_id()); jmethodID java_instance_id_method = instance_id::GetMethodId(instance_id::kDeleteToken); operation->ReleaseExecuteCancelLock(); env->CallVoidMethod(java_instance_id, java_instance_id_method, entity_jstring, scope_jstring); std::string error = util::GetAndClearExceptionMessage(env); env->DeleteLocalRef(java_instance_id); env->DeleteLocalRef(entity_jstring); env->DeleteLocalRef(scope_jstring); if (operation->AcquireExecuteCancelLock()) { instance_id_internal->CompleteOperation( operation, ExceptionStringToError(error.c_str()), error.c_str()); } }, &(*operation), InstanceIdInternal::Canceled, &(*operation)); return DeleteTokenLastResult(); } InstanceId* InstanceId::GetInstanceId(App* app, InitResult* init_result_out) { FIREBASE_ASSERT_MESSAGE_RETURN(nullptr, app, "App must be specified."); FIREBASE_UTIL_RETURN_NULL_IF_GOOGLE_PLAY_UNAVAILABLE(*app, init_result_out); MutexLock lock(InstanceIdInternal::mutex()); if (init_result_out) *init_result_out = kInitResultSuccess; auto instance_id = InstanceIdInternal::FindInstanceIdByApp(app); if (instance_id) return instance_id; if (!Initialize(*app)) { if (init_result_out) *init_result_out = kInitResultFailedMissingDependency; return nullptr; } JNIEnv* env = app->GetJNIEnv(); jobject platform_app = app->GetPlatformApp(); jobject java_instance_id = env->CallStaticObjectMethod( instance_id::GetClass(), instance_id::GetMethodId(instance_id::kGetInstance), platform_app); env->DeleteLocalRef(platform_app); if (firebase::util::CheckAndClearJniExceptions(env) || !java_instance_id) { Terminate(*app); if (init_result_out) *init_result_out = kInitResultFailedMissingDependency; return nullptr; } InstanceIdInternal* instance_id_internal = new InstanceIdInternal(); instance_id = new InstanceId(app, instance_id_internal); instance_id_internal->Initialize(instance_id, java_instance_id); return instance_id; } } // namespace instance_id } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_PROMISE_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_PROMISE_ANDROID_H_ #include <jni.h> #include "app/src/reference_counted_future_impl.h" #include "app/src/util_android.h" #include "firestore/src/android/document_snapshot_android.h" #include "firestore/src/android/firebase_firestore_exception_android.h" #include "firestore/src/android/firestore_android.h" #include "firestore/src/android/query_snapshot_android.h" namespace firebase { namespace firestore { // This class simplifies the implementation of Future APIs for Android wrappers. // PublicType is the public type, say Foo, and InternalType is FooInternal, // which is required to be a subclass of WrapperFuture. FnEnumType is an enum // class that defines a set of APIs returning a Future. For example, to // implement Future<DocumentReference> CollectionReferenceInternal::Add(), // PublicType is DocumentReference, InternalType is DocumentReferenceInternal, // and FnEnumType is CollectionReferenceFn. template <typename PublicType, typename InternalType, typename FnEnumType> class Promise { public: // One can add a completion to execute right after the Future is resolved. // The Games's Future library does not support chaining-up of completions yet. // So we add the interface here to allow executing code after Future is // resolved. template <typename PublicT> class Completion { public: virtual ~Completion() {} virtual void CompleteWith(Error error_code, const char* error_message, PublicT* result) = 0; }; Promise(ReferenceCountedFutureImpl* impl, FirestoreInternal* firestore, Completion<PublicType>* completion = nullptr) : completer_{new Completer<PublicType, InternalType>{impl, firestore, completion}}, impl_(impl) {} ~Promise() { delete completer_; } void RegisterForTask(FnEnumType op, jobject task) { JNIEnv* env = completer_->firestore()->app()->GetJNIEnv(); handle_ = completer_->Alloc(static_cast<int>(op)); // Ownership of the completer will pass to to RegisterCallbackOnTask Completer<PublicType, InternalType>* completer = completer_; completer_ = nullptr; util::RegisterCallbackOnTask(env, task, ResultCallback, completer, kApiIdentifier); } Future<PublicType> GetFuture() { return MakeFuture(impl_, handle_); } private: template <typename PublicT> class CompleterBase { public: CompleterBase(ReferenceCountedFutureImpl* impl, FirestoreInternal* firestore, Completion<PublicT>* completion) : impl_{impl}, firestore_{firestore}, completion_(completion) {} virtual ~CompleterBase() {} FirestoreInternal* firestore() { return firestore_; } SafeFutureHandle<PublicT> Alloc(int fn_index) { handle_ = impl_->SafeAlloc<PublicT>(fn_index); return handle_; } virtual void CompleteWithResult(jobject result, util::FutureResult result_code, const char* status_message) { // result can be either the resolved object or exception, depending on // result_code. if (result_code == util::kFutureResultSuccess) { // When succeeded, result is the resolved object of the Future. SucceedWithResult(result); return; } Error error_code = Unknown; switch (result_code) { case util::kFutureResultFailure: // When failed, result is the exception raised. error_code = FirebaseFirestoreExceptionInternal::ToErrorCode( this->firestore_->app()->GetJNIEnv(), result); break; case util::kFutureResultCancelled: error_code = Cancelled; break; default: error_code = Unknown; FIREBASE_ASSERT_MESSAGE(false, "unknown FutureResult %d", result_code); break; } this->impl_->Complete(this->handle_, error_code, status_message); if (this->completion_ != nullptr) { this->completion_->CompleteWith(error_code, status_message, nullptr); } delete this; } virtual void SucceedWithResult(jobject result) = 0; protected: SafeFutureHandle<PublicT> handle_; ReferenceCountedFutureImpl* impl_; // not owning FirestoreInternal* firestore_; // not owning Completion<PublicType>* completion_; // not owning }; // Partial specialization of a nested class is allowed. So adding the no-op // Dummy parameter just to suppress the error: // explicit specialization of 'Completer' in class scope template <typename PublicT, typename InternalT, typename Dummy = void> class Completer : public CompleterBase<PublicT> { public: using CompleterBase<PublicT>::CompleterBase; void SucceedWithResult(jobject result) override { PublicT future_result = FirestoreInternal::Wrap<InternalT>( new InternalT(this->firestore_, result)); this->impl_->CompleteWithResult(this->handle_, Ok, /*error_msg=*/"", future_result); if (this->completion_ != nullptr) { this->completion_->CompleteWith(Ok, /*error_message*/ "", &future_result); } delete this; } }; template <typename Dummy> class Completer<void, void, Dummy> : public CompleterBase<void> { public: using CompleterBase<void>::CompleterBase; void SucceedWithResult(jobject result) override { this->impl_->Complete(this->handle_, Ok, /*error_msg=*/""); if (this->completion_ != nullptr) { this->completion_->CompleteWith(Ok, /*error_message*/ "", nullptr); } delete this; } }; static void ResultCallback(JNIEnv* env, jobject result, util::FutureResult result_code, const char* status_message, void* callback_data) { if (callback_data != nullptr) { auto* data = static_cast<Completer<PublicType, InternalType>*>(callback_data); data->CompleteWithResult(result, result_code, status_message); } } Completer<PublicType, InternalType>* completer_; // Keep these values separate from the Completer in case completion happens // before the future is constructed. ReferenceCountedFutureImpl* impl_; SafeFutureHandle<PublicType> handle_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_PROMISE_ANDROID_H_ <file_sep>#include "firestore/src/include/firebase/firestore/document_snapshot.h" #include <ostream> #include <utility> #include "app/src/assert.h" #include "firestore/src/common/cleanup.h" #include "firestore/src/common/util.h" #include "firestore/src/common/to_string.h" #include "firestore/src/include/firebase/firestore/document_reference.h" #include "firestore/src/include/firebase/firestore/field_path.h" #include "firestore/src/include/firebase/firestore/field_value.h" #if defined(__ANDROID__) #include "firestore/src/android/document_snapshot_android.h" #elif defined(FIRESTORE_STUB_BUILD) #include "firestore/src/stub/document_snapshot_stub.h" #else #include "firestore/src/ios/document_snapshot_ios.h" #endif // defined(__ANDROID__) namespace firebase { namespace firestore { using CleanupFnDocumentSnapshot = CleanupFn<DocumentSnapshot, DocumentSnapshotInternal>; DocumentSnapshot::DocumentSnapshot() {} DocumentSnapshot::DocumentSnapshot(const DocumentSnapshot& snapshot) { if (snapshot.internal_) { internal_ = new DocumentSnapshotInternal(*snapshot.internal_); } CleanupFnDocumentSnapshot::Register(this, internal_); } DocumentSnapshot::DocumentSnapshot(DocumentSnapshot&& snapshot) { CleanupFnDocumentSnapshot::Unregister(&snapshot, snapshot.internal_); std::swap(internal_, snapshot.internal_); CleanupFnDocumentSnapshot::Register(this, internal_); } DocumentSnapshot::DocumentSnapshot(DocumentSnapshotInternal* internal) : internal_(internal) { FIREBASE_ASSERT(internal != nullptr); CleanupFnDocumentSnapshot::Register(this, internal_); } DocumentSnapshot::~DocumentSnapshot() { CleanupFnDocumentSnapshot::Unregister(this, internal_); delete internal_; internal_ = nullptr; } DocumentSnapshot& DocumentSnapshot::operator=( const DocumentSnapshot& snapshot) { if (this == &snapshot) { return *this; } CleanupFnDocumentSnapshot::Unregister(this, internal_); delete internal_; if (snapshot.internal_) { internal_ = new DocumentSnapshotInternal(*snapshot.internal_); } else { internal_ = nullptr; } CleanupFnDocumentSnapshot::Register(this, internal_); return *this; } DocumentSnapshot& DocumentSnapshot::operator=(DocumentSnapshot&& snapshot) { if (this == &snapshot) { return *this; } CleanupFnDocumentSnapshot::Unregister(&snapshot, snapshot.internal_); CleanupFnDocumentSnapshot::Unregister(this, internal_); delete internal_; internal_ = snapshot.internal_; snapshot.internal_ = nullptr; CleanupFnDocumentSnapshot::Register(this, internal_); return *this; } const std::string& DocumentSnapshot::id() const { if (!internal_) return EmptyString(); return internal_->id(); } DocumentReference DocumentSnapshot::reference() const { if (!internal_) return {}; return internal_->reference(); } SnapshotMetadata DocumentSnapshot::metadata() const { if (!internal_) return SnapshotMetadata{false, false}; return internal_->metadata(); } bool DocumentSnapshot::exists() const { if (!internal_) return {}; return internal_->exists(); } MapFieldValue DocumentSnapshot::GetData(ServerTimestampBehavior stb) const { if (!internal_) return MapFieldValue{}; return internal_->GetData(stb); } FieldValue DocumentSnapshot::Get(const char* field, ServerTimestampBehavior stb) const { if (!internal_) return {}; return internal_->Get(FieldPath::FromDotSeparatedString(field), stb); } FieldValue DocumentSnapshot::Get(const std::string& field, ServerTimestampBehavior stb) const { if (!internal_) return {}; return internal_->Get(FieldPath::FromDotSeparatedString(field), stb); } FieldValue DocumentSnapshot::Get(const FieldPath& field, ServerTimestampBehavior stb) const { if (!internal_) return {}; return internal_->Get(field, stb); } std::string DocumentSnapshot::ToString() const { if (!internal_) return "DocumentSnapshot(invalid)"; return std::string("DocumentSnapshot(id=") + id() + ", metadata=" + metadata().ToString() + ", doc=" + ::firebase::firestore::ToString(GetData()) + ')'; } std::ostream& operator<<(std::ostream& out, const DocumentSnapshot& document) { return out << document.ToString(); } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_MAP_HELPER_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_MAP_HELPER_H_ #include <string> #include <vector> #include "app/meta/move.h" #include "firebase/firestore/field_path.h" #include "firebase/firestore/field_value.h" #include "firebase/firestore/map_field_value.h" namespace firebase { namespace firestore { namespace csharp { // FieldValue is converted to FieldValueInternal of internal access, which // makes it impossible to use standard containers. What's more, // MapFieldValue type depends on compilation settings. Providing the helper // here, we provide a more transparent layer for C# calls. // We cannot call std::vector<FieldValue>::foo() in C# since it is not // exposed via the .dll interface as SWIG cannot convert it. Here we // essentially define a function, which SWIG can convert and thus expose it // via the .dll. So C# code can call it. // It is OK to re-construct a vector of strings since those strings can be // re-used by the C# code. This way is more clean than to expose an // iterator. inline std::vector<std::string> map_fv_keys(const MapFieldValue& self) { std::vector<std::string> result; result.reserve(self.size()); for (const auto& kv : self) { result.push_back(kv.first); } return result; } inline const FieldValue& map_fv_get(const MapFieldValue& self, const std::string& key) { return self.at(key); } inline MapFieldValue map_fv_create() { return MapFieldValue{}; } inline void map_fv_set(MapFieldValue* self, const std::string& key, FieldValue value) { // This could be either a move-assignment or a normal assignment. (*self)[key] = firebase::Move(value); } inline MapFieldPathValue map_fpv_create() { return MapFieldPathValue{}; } inline void map_set(MapFieldPathValue* self, FieldPath key, FieldValue value) { // These could be either move or copy. (*self)[firebase::Move(key)] = firebase::Move(value); } } // namespace csharp } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_MAP_HELPER_H_ <file_sep>#include "firestore/src/ios/query_snapshot_ios.h" #include <utility> #include "firestore/src/ios/converter_ios.h" #include "firestore/src/ios/document_change_ios.h" #include "firestore/src/ios/document_snapshot_ios.h" #include "firestore/src/ios/query_ios.h" #include "firestore/src/ios/util_ios.h" namespace firebase { namespace firestore { QuerySnapshotInternal::QuerySnapshotInternal(api::QuerySnapshot&& snapshot) : snapshot_{std::move(snapshot)} {} FirestoreInternal* QuerySnapshotInternal::firestore_internal() { return GetFirestoreInternal(&snapshot_); } Query QuerySnapshotInternal::query() const { return MakePublic(snapshot_.query()); } SnapshotMetadata QuerySnapshotInternal::metadata() const { const auto& result = snapshot_.metadata(); return SnapshotMetadata{result.pending_writes(), result.from_cache()}; } std::size_t QuerySnapshotInternal::size() const { return snapshot_.size(); } std::vector<DocumentChange> QuerySnapshotInternal::DocumentChanges( MetadataChanges metadata_changes) const { bool include_metadata = metadata_changes == MetadataChanges::kInclude; if (!document_changes_ || changes_include_metadata_ != include_metadata) { std::vector<DocumentChange> result; snapshot_.ForEachChange(include_metadata, [&result](api::DocumentChange change) { result.push_back(MakePublic(std::move(change))); }); document_changes_ = std::move(result); changes_include_metadata_ = include_metadata; } return document_changes_.value(); } std::vector<DocumentSnapshot> QuerySnapshotInternal::documents() const { if (!documents_) { std::vector<DocumentSnapshot> result; snapshot_.ForEachDocument([&result](api::DocumentSnapshot snapshot) { result.push_back(MakePublic(std::move(snapshot))); }); documents_ = result; } return documents_.value(); } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_LISTENER_REGISTRATION_STUB_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_LISTENER_REGISTRATION_STUB_H_ #include "firestore/src/stub/firestore_stub.h" namespace firebase { namespace firestore { // This is the stub implementation of ListenerRegistration. class ListenerRegistrationInternal { public: using ApiType = ListenerRegistration; FirestoreInternal* firestore_internal() { return nullptr; } }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_LISTENER_REGISTRATION_STUB_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_COLLECTION_REFERENCE_STUB_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_COLLECTION_REFERENCE_STUB_H_ #include <string> #include "app/src/include/firebase/app.h" #include "firestore/src/common/futures.h" #include "firestore/src/include/firebase/firestore/collection_reference.h" #include "firestore/src/include/firebase/firestore/document_reference.h" #include "firestore/src/stub/firestore_stub.h" #include "firestore/src/stub/query_stub.h" namespace firebase { namespace firestore { // This is the stub implementation of CollectionReference. class CollectionReferenceInternal : public QueryInternal { public: using ApiType = CollectionReference; FirestoreInternal* firestore_internal() { return nullptr; } const std::string& id() { return id_; } const std::string& path() { return id_; } DocumentReference Parent() const { return DocumentReference{}; } DocumentReference Document() const { return DocumentReference{}; } DocumentReference Document(const std::string& document_path) const { return DocumentReference{}; } Future<DocumentReference> Add(const MapFieldValue& data) { return FailedFuture<DocumentReference>(); } Future<DocumentReference> AddLastResult() { return FailedFuture<DocumentReference>(); } private: std::string id_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_COLLECTION_REFERENCE_STUB_H_ <file_sep>#include "firestore/src/stub/firestore_stub.h" #include "firestore/src/include/firebase/firestore.h" namespace firebase { namespace firestore { /* static */ void Firestore::set_logging_enabled(bool logging_enabled) {} } // namespace firestore } // namespace firebase <file_sep>#include "firestore/src/ios/document_change_ios.h" #include <utility> #include "firestore/src/ios/converter_ios.h" #include "firestore/src/ios/document_snapshot_ios.h" #include "firestore/src/ios/hard_assert_ios.h" #include "firestore/src/ios/util_ios.h" namespace firebase { namespace firestore { using Type = DocumentChange::Type; DocumentChangeInternal::DocumentChangeInternal(api::DocumentChange&& change) : change_{std::move(change)} {} FirestoreInternal* DocumentChangeInternal::firestore_internal() { return GetFirestoreInternal(&change_); } Type DocumentChangeInternal::type() const { switch (change_.type()) { case api::DocumentChange::Type::Added: return Type::kAdded; case api::DocumentChange::Type::Modified: return Type::kModified; case api::DocumentChange::Type::Removed: return Type::kRemoved; } UNREACHABLE(); } DocumentSnapshot DocumentChangeInternal::document() const { return MakePublic(change_.document()); } std::size_t DocumentChangeInternal::old_index() const { return change_.old_index(); } std::size_t DocumentChangeInternal::new_index() const { return change_.new_index(); } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_SOURCE_IOS_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_SOURCE_IOS_H_ #include "firestore/src/include/firebase/firestore/source.h" #include "firestore/src/ios/hard_assert_ios.h" #include "Firestore/core/src/firebase/firestore/api/source.h" namespace firebase { namespace firestore { inline api::Source ToCoreApi(Source source) { switch (source) { case Source::kDefault: return api::Source::Default; case Source::kServer: return api::Source::Server; case Source::kCache: return api::Source::Cache; } UNREACHABLE(); } } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_SOURCE_IOS_H_ <file_sep>/* * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FIREBASE_APP_CLIENT_CPP_META_TYPE_TRAITS_H_ #define FIREBASE_APP_CLIENT_CPP_META_TYPE_TRAITS_H_ #include <cstdlib> #if !defined(FIREBASE_NAMESPACE) #define FIREBASE_NAMESPACE firebase #endif namespace FIREBASE_NAMESPACE { template <typename T> struct remove_reference { typedef T type; }; template <typename T> struct remove_reference<T&> { typedef T type; }; template <typename T> struct remove_reference<T&&> { typedef T type; }; template <typename T> struct is_array { static const bool value = false; }; template <typename T> struct is_array<T[]> { static const bool value = true; }; template <typename T, std::size_t N> struct is_array<T[N]> { static const bool value = true; }; template <typename T> struct is_lvalue_reference { static const bool value = false; }; template <typename T> struct is_lvalue_reference<T&> { static const bool value = true; }; // NOLINTNEXTLINE - allow namespace overridden } // namespace FIREBASE_NAMESPACE #endif // FIREBASE_APP_CLIENT_CPP_META_TYPE_TRAITS_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_FIRESTORE_STUB_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_FIRESTORE_STUB_H_ #include "app/src/cleanup_notifier.h" #include "firestore/src/common/futures.h" #include "firestore/src/include/firebase/firestore.h" namespace firebase { namespace firestore { class FirestoreInternal; // There is no internal type for stub (yet). We define these stubs to suppress // incomplete type error for now. class Stub { public: FirestoreInternal* firestore_internal() { return nullptr; } }; // This is the stub implementation of Firestore. class FirestoreInternal { public: using ApiType = Firestore; explicit FirestoreInternal(App* app) : app_(app) {} ~FirestoreInternal() {} App* app() const { return app_; } // Whether this object was successfully initialized by the constructor. bool initialized() const { return app_ != nullptr; } // Default CleanupNotifier as required by the shared code; nothing more. CleanupNotifier& cleanup() { return cleanup_; } // Do nothing yet for the stub. void set_logging_enabled(bool logging_enabled) {} // Returns a null Collection. CollectionReference Collection(const char* collection_path) const { return CollectionReference{}; } // Returns a null Document. DocumentReference Document(const char* document_path) const { return DocumentReference{}; } // Returns a null Query. Query CollectionGroup(const char* collection_id) const { return Query{}; } // Gets the settings class member. Has no effect to the stub yet. Settings settings() const { return settings_; } // Sets the settings class member. Has no effect to the stub yet. void set_settings(const Settings& settings) { settings_ = settings; } WriteBatch batch() const { return WriteBatch{}; } // Runs transaction atomically. Future<void> RunTransaction(TransactionFunction* update) { return FailedFuture<void>(); } #if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) Future<void> RunTransaction( std::function<Error(Transaction*, std::string*)> update) { return FailedFuture<void>(); } #endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) Future<void> RunTransactionLastResult() { return FailedFuture<void>(); } // Disables network and gets anything from cache instead of server. Future<void> DisableNetwork() { return FailedFuture<void>(); } Future<void> DisableNetworkLastResult() { return FailedFuture<void>(); } // Re-enables network after a prior call to DisableNetwork(). Future<void> EnableNetwork() { return FailedFuture<void>(); } Future<void> EnableNetworkLastResult() { return FailedFuture<void>(); } Future<void> Terminate() { return FailedFuture<void>(); } Future<void> TerminateLastResult() { return FailedFuture<void>(); } Future<void> WaitForPendingWrites() { return FailedFuture<void>(); } Future<void> WaitForPendingWritesLastResult() { return FailedFuture<void>(); } Future<void> ClearPersistence() { return FailedFuture<void>(); } Future<void> ClearPersistenceLastResult() { return FailedFuture<void>(); } ListenerRegistration AddSnapshotsInSyncListener( EventListener<void>* listener) { return ListenerRegistration{}; } #if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) ListenerRegistration AddSnapshotsInSyncListener( // NOLINTNEXTLINE (performance-unnecessary-value-param) std::function<void()> callback) { return ListenerRegistration{}; } #endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) void UnregisterListenerRegistration( ListenerRegistrationInternal* registration) {} // The following builders are test helpers to avoid expose the details into // public header. template <typename InternalType> static typename InternalType::ApiType Wrap(InternalType* internal) { return typename InternalType::ApiType(internal); } template <typename InternalType> static InternalType* Internal(typename InternalType::ApiType& value) { // Cast is required for the case when the InternalType has hierachy e.g. // CollectionReferenceInternal vs QueryInternal (check their implementation // for more details). return static_cast<InternalType*>(value.internal_); } void set_firestore_public(Firestore*) {} private: CleanupNotifier cleanup_; App* app_; Settings settings_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_FIRESTORE_STUB_H_ <file_sep>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "instance_id/src/desktop/instance_id_internal.h" namespace firebase { namespace instance_id { namespace internal { InstanceIdInternal::InstanceIdInternal(App* app) : InstanceIdInternalBase(), safe_ref_(this) { impl_ = InstanceIdDesktopImpl::GetInstance(app); } InstanceIdInternal::~InstanceIdInternal() { safe_ref_.ClearReference(); // App will make sure impl_ gets deleted. } } // namespace internal } // namespace instance_id } // namespace firebase <file_sep>#include "firestore/src/android/set_options_android.h" #include <jni.h> #include <utility> #include "app/src/util_android.h" #include "firestore/src/android/field_path_android.h" #include "firestore/src/android/util_android.h" namespace firebase { namespace firestore { using Type = SetOptions::Type; // clang-format off #define SET_OPTIONS_METHODS(X) \ X(Merge, "merge", \ "()Lcom/google/firebase/firestore/SetOptions;", \ firebase::util::kMethodTypeStatic), \ X(MergeFieldPaths, "mergeFieldPaths", \ "(Ljava/util/List;)Lcom/google/firebase/firestore/SetOptions;", \ firebase::util::kMethodTypeStatic) #define SET_OPTIONS_FIELDS(X) \ X(Overwrite, "OVERWRITE", "Lcom/google/firebase/firestore/SetOptions;", \ util::kFieldTypeStatic) // clang-format on METHOD_LOOKUP_DECLARATION(set_options, SET_OPTIONS_METHODS, SET_OPTIONS_FIELDS) METHOD_LOOKUP_DEFINITION(set_options, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/SetOptions", SET_OPTIONS_METHODS, SET_OPTIONS_FIELDS) /* static */ jobject SetOptionsInternal::Overwrite(JNIEnv* env) { jobject result = env->GetStaticObjectField( set_options::GetClass(), set_options::GetFieldId(set_options::kOverwrite)); CheckAndClearJniExceptions(env); return result; } /* static */ jobject SetOptionsInternal::Merge(JNIEnv* env) { jobject result = env->CallStaticObjectMethod( set_options::GetClass(), set_options::GetMethodId(set_options::kMerge)); CheckAndClearJniExceptions(env); return result; } /* static */ jobject SetOptionsInternal::ToJavaObject(JNIEnv* env, const SetOptions& set_options) { switch (set_options.type_) { case Type::kOverwrite: return Overwrite(env); case Type::kMergeAll: return Merge(env); case Type::kMergeSpecific: // Do below this switch. break; default: FIREBASE_ASSERT_MESSAGE(false, "Unknown SetOptions type."); return nullptr; } // Now we deal with options to merge specific fields. // Construct call arguments. jobject fields = env->NewObject( util::array_list::GetClass(), util::array_list::GetMethodId(util::array_list::kConstructor)); jmethodID add_method = util::array_list::GetMethodId(util::array_list::kAdd); for (const FieldPath& field : set_options.fields_) { jobject field_converted = FieldPathConverter::ToJavaObject(env, field); env->CallBooleanMethod(fields, add_method, field_converted); CheckAndClearJniExceptions(env); env->DeleteLocalRef(field_converted); } // Make the call to Android SDK. jobject result = env->CallStaticObjectMethod( set_options::GetClass(), set_options::GetMethodId(set_options::kMergeFieldPaths), fields); CheckAndClearJniExceptions(env); env->DeleteLocalRef(fields); return result; } /* static */ bool SetOptionsInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = set_options::CacheMethodIds(env, activity) && set_options::CacheFieldIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void SetOptionsInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); set_options::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>#include "firestore/src/android/event_listener_android.h" #include <utility> #include "app/src/embedded_file.h" #include "app/src/include/firebase/app.h" #include "app/src/include/firebase/internal/common.h" #include "app/src/util_android.h" #include "firestore/src/android/document_snapshot_android.h" #include "firestore/src/android/firebase_firestore_exception_android.h" #include "firestore/src/android/query_snapshot_android.h" #include "firestore/src/android/util_android.h" #include "firestore/src/include/firebase/firestore/query_snapshot.h" #include "firebase/firestore/firestore_errors.h" namespace firebase { namespace firestore { #define CPP_EVENT_LISTENER_METHODS(X) \ X(DiscardPointers, "discardPointers", "()V") METHOD_LOOKUP_DECLARATION(cpp_event_listener, CPP_EVENT_LISTENER_METHODS) METHOD_LOOKUP_DEFINITION( cpp_event_listener, "com/google/firebase/firestore/internal/cpp/CppEventListener", CPP_EVENT_LISTENER_METHODS) #define DOCUMENT_EVENT_LISTENER_METHODS(X) X(Constructor, "<init>", "(JJ)V") METHOD_LOOKUP_DECLARATION(document_event_listener, DOCUMENT_EVENT_LISTENER_METHODS) METHOD_LOOKUP_DEFINITION( document_event_listener, "com/google/firebase/firestore/internal/cpp/DocumentEventListener", DOCUMENT_EVENT_LISTENER_METHODS) #define QUERY_EVENT_LISTENER_METHODS(X) X(Constructor, "<init>", "(JJ)V") METHOD_LOOKUP_DECLARATION(query_event_listener, QUERY_EVENT_LISTENER_METHODS) METHOD_LOOKUP_DEFINITION( query_event_listener, "com/google/firebase/firestore/internal/cpp/QueryEventListener", QUERY_EVENT_LISTENER_METHODS) #define VOID_EVENT_LISTENER_METHODS(X) X(Constructor, "<init>", "(J)V") METHOD_LOOKUP_DECLARATION(void_event_listener, VOID_EVENT_LISTENER_METHODS) METHOD_LOOKUP_DEFINITION( void_event_listener, "com/google/firebase/firestore/internal/cpp/VoidEventListener", VOID_EVENT_LISTENER_METHODS) /* static */ void EventListenerInternal::DocumentEventListenerNativeOnEvent( JNIEnv* env, jclass clazz, jlong firestore_ptr, jlong listener_ptr, jobject value, jobject error) { if (firestore_ptr == 0 || listener_ptr == 0) { return; } EventListener<DocumentSnapshot>* listener = reinterpret_cast<EventListener<DocumentSnapshot>*>(listener_ptr); Error error_code = FirebaseFirestoreExceptionInternal::ToErrorCode(env, error); if (error_code != Ok) { listener->OnEvent(DocumentSnapshot{}, error_code); return; } FirestoreInternal* firestore = reinterpret_cast<FirestoreInternal*>(firestore_ptr); DocumentSnapshot snapshot(new DocumentSnapshotInternal{firestore, value}); listener->OnEvent(snapshot, error_code); } /* static */ void EventListenerInternal::QueryEventListenerNativeOnEvent( JNIEnv* env, jclass clazz, jlong firestore_ptr, jlong listener_ptr, jobject value, jobject error) { if (firestore_ptr == 0 || listener_ptr == 0) { return; } EventListener<QuerySnapshot>* listener = reinterpret_cast<EventListener<QuerySnapshot>*>(listener_ptr); Error error_code = FirebaseFirestoreExceptionInternal::ToErrorCode(env, error); if (error_code != Ok) { listener->OnEvent(QuerySnapshot{}, error_code); return; } FirestoreInternal* firestore = reinterpret_cast<FirestoreInternal*>(firestore_ptr); QuerySnapshot snapshot(new QuerySnapshotInternal{firestore, value}); listener->OnEvent(snapshot, error_code); } /* static */ void EventListenerInternal::VoidEventListenerNativeOnEvent(JNIEnv* env, jclass clazz, jlong listener_ptr) { if (listener_ptr == 0) { return; } EventListener<void>* listener = reinterpret_cast<EventListener<void>*>(listener_ptr); listener->OnEvent(Error::Ok); } /* static */ jobject EventListenerInternal::EventListenerToJavaEventListener( JNIEnv* env, FirestoreInternal* firestore, EventListener<DocumentSnapshot>* listener) { jobject result = env->NewObject(document_event_listener::GetClass(), document_event_listener::GetMethodId( document_event_listener::kConstructor), reinterpret_cast<jlong>(firestore), reinterpret_cast<jlong>(listener)); CheckAndClearJniExceptions(env); return result; } /* static */ jobject EventListenerInternal::EventListenerToJavaEventListener( JNIEnv* env, FirestoreInternal* firestore, EventListener<QuerySnapshot>* listener) { jobject result = env->NewObject( query_event_listener::GetClass(), query_event_listener::GetMethodId(query_event_listener::kConstructor), reinterpret_cast<jlong>(firestore), reinterpret_cast<jlong>(listener)); CheckAndClearJniExceptions(env); return result; } /* static */ jobject EventListenerInternal::EventListenerToJavaRunnable( JNIEnv* env, EventListener<void>* listener) { jobject result = env->NewObject( void_event_listener::GetClass(), void_event_listener::GetMethodId(void_event_listener::kConstructor), reinterpret_cast<jlong>(listener)); CheckAndClearJniExceptions(env); return result; } /* static */ bool EventListenerInternal::InitializeEmbeddedClasses( App* app, const std::vector<internal::EmbeddedFile>* embedded_files) { static const JNINativeMethod kDocumentEventListenerNatives[] = { {"nativeOnEvent", "(JJLjava/lang/Object;Lcom/google/firebase/firestore/" "FirebaseFirestoreException;)V", reinterpret_cast<void*>( &EventListenerInternal::DocumentEventListenerNativeOnEvent)}}; static const JNINativeMethod kQueryEventListenerNatives[] = { {"nativeOnEvent", "(JJLjava/lang/Object;Lcom/google/firebase/firestore/" "FirebaseFirestoreException;)V", reinterpret_cast<void*>( &EventListenerInternal::QueryEventListenerNativeOnEvent)}}; static const JNINativeMethod kVoidEventListenerNatives[] = { {"nativeOnEvent", "(J)V", reinterpret_cast<void*>( &EventListenerInternal::VoidEventListenerNativeOnEvent)}}; JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = // Cache classes cpp_event_listener::CacheClassFromFiles(env, activity, embedded_files) && document_event_listener::CacheClassFromFiles(env, activity, embedded_files) && query_event_listener::CacheClassFromFiles(env, activity, embedded_files) && void_event_listener::CacheClassFromFiles(env, activity, embedded_files) && // Cache method-ids cpp_event_listener::CacheMethodIds(env, activity) && document_event_listener::CacheMethodIds(env, activity) && query_event_listener::CacheMethodIds(env, activity) && void_event_listener::CacheMethodIds(env, activity) && // Register natives document_event_listener::RegisterNatives( env, kDocumentEventListenerNatives, FIREBASE_ARRAYSIZE(kDocumentEventListenerNatives)) && query_event_listener::RegisterNatives( env, kQueryEventListenerNatives, FIREBASE_ARRAYSIZE(kQueryEventListenerNatives)) && void_event_listener::RegisterNatives( env, kVoidEventListenerNatives, FIREBASE_ARRAYSIZE(kVoidEventListenerNatives)); util::CheckAndClearJniExceptions(env); return result; } /* static */ void EventListenerInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); // Release embedded classes. cpp_event_listener::ReleaseClass(env); document_event_listener::ReleaseClass(env); query_event_listener::ReleaseClass(env); void_event_listener::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef FIREBASE_INSTANCE_ID_CLIENT_CPP_SRC_ANDROID_INSTANCE_ID_INTERNAL_H_ #define FIREBASE_INSTANCE_ID_CLIENT_CPP_SRC_ANDROID_INSTANCE_ID_INTERNAL_H_ #include <assert.h> #include <jni.h> #include <vector> #include "app/memory/shared_ptr.h" #include "app/src/include/firebase/app.h" #include "app/src/reference_counted_future_impl.h" #include "app/src/util_android.h" #include "instance_id/src/include/firebase/instance_id.h" #include "instance_id/src/instance_id_internal_base.h" namespace firebase { namespace instance_id { namespace internal { // Context for async operations on Android. class AsyncOperation : public util::JavaThreadContext { public: AsyncOperation(JNIEnv* env, InstanceIdInternal* instance_id_internal, FutureHandle future_handle) : JavaThreadContext(env), derived_(nullptr), instance_id_internal_(instance_id_internal), future_handle_(future_handle) {} virtual ~AsyncOperation() {} // Get the InstanceId. InstanceIdInternal* instance_id_internal() const { return instance_id_internal_; } // Get the future handle from this context. template <typename T> SafeFutureHandle<T> future_handle() const { return SafeFutureHandle<T>(future_handle_); } // Get the derived class pointer from this class. void* derived() const { return derived_; } protected: void* derived_; private: InstanceIdInternal* instance_id_internal_; FutureHandle future_handle_; }; // Android specific instance ID data. class InstanceIdInternal : public InstanceIdInternalBase { public: // This class must be initialized with Initialize() prior to use. InstanceIdInternal(); // Delete the global reference to the Java InstanceId object. ~InstanceIdInternal(); // Add a global reference to the specified Java InstanceId object and // delete the specified local reference. // set_instance_id() must be called before this. void Initialize(InstanceId* instance_id, jobject java_instance_id); // Get the Java InstanceId class. jobject java_instance_id() const { return java_instance_id_; } // Get the InstanceId object. InstanceId* instance_id() const { return instance_id_; } // Store a reference to a scheduled operation. SharedPtr<AsyncOperation> AddOperation(AsyncOperation* operation); // Find the SharedPtr to the operation using raw pointer. SharedPtr<AsyncOperation> GetOperationSharedPtr(AsyncOperation* operation); // Remove a reference to a schedule operation. void RemoveOperation(const SharedPtr<AsyncOperation>& operation); // Cancel all scheduled operations. void CancelOperations(); // Complete the future associated with the specified operation and delete the // operation. template <typename T> void CompleteOperationWithResult(const SharedPtr<AsyncOperation>& operation, const T& result, Error error = kErrorNone, const char* error_message = nullptr) { future_api().CompleteWithResult(operation->future_handle<T>(), error, error_message ? error_message : "", result); RemoveOperation(operation); } // Complete the future associated with the specified operation and delete the // operation. void CompleteOperation(const SharedPtr<AsyncOperation>& operation, Error error = kErrorNone, const char* error_message = nullptr); private: // Cancel the future associated with the specified operation and delete // the operation. template <typename T> void CancelOperationWithResult(const SharedPtr<AsyncOperation>& operation) { CompleteOperationWithResult(operation, T(), kErrorUnknown, kCancelledError); } // Cancel the future associated with the specified operation and delete // the operation. void CancelOperation(const SharedPtr<AsyncOperation>& operation) { CompleteOperation(operation, kErrorUnknown, kCancelledError); } public: // Complete a future with an error when an operation is canceled. template <typename T> static void CanceledWithResult(void* function_data) { AsyncOperation* ptr = static_cast<AsyncOperation*>(function_data); // Hold a reference to AsyncOperation so that it will not be deleted during // this callback. SharedPtr<AsyncOperation> operation = ptr->instance_id_internal()->GetOperationSharedPtr(ptr); if (!operation) return; operation->instance_id_internal()->CancelOperationWithResult<T>(operation); } static void Canceled(void* function_data); private: // End user's InstanceId interface. InstanceId* instance_id_; // Java object instance. jobject java_instance_id_; std::vector<SharedPtr<AsyncOperation>> operations_; // Guards operations_. Mutex operations_mutex_; static const char* kCancelledError; }; } // namespace internal } // namespace instance_id } // namespace firebase #endif // FIREBASE_INSTANCE_ID_CLIENT_CPP_SRC_ANDROID_INSTANCE_ID_INTERNAL_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_DIRECTION_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_DIRECTION_ANDROID_H_ #include "app/src/include/firebase/app.h" #include "app/src/util_android.h" #include "firestore/src/android/query_android.h" namespace firebase { namespace firestore { class DirectionInternal { public: static jobject ToJavaObject(JNIEnv* env, Query::Direction direction); private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); static jobject ascending_; static jobject descending_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_DIRECTION_ANDROID_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_SET_OPTIONS_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_SET_OPTIONS_ANDROID_H_ #include <jni.h> #include "app/src/include/firebase/app.h" #include "firestore/src/include/firebase/firestore/set_options.h" namespace firebase { namespace firestore { /** * This helper class provides conversion between the C++ type and Java type. In * addition, we also need proper initializer and terminator for the Java class * cache/uncache. */ class SetOptionsInternal { public: using ApiType = SetOptions; /** Get a jobject for overwrite option. */ static jobject Overwrite(JNIEnv* env); /** Get a jobject for merge all option. */ static jobject Merge(JNIEnv* env); /** Convert a C++ SetOptions to a Java SetOptions. */ static jobject ToJavaObject(JNIEnv* env, const SetOptions& set_options); // We do not need to convert Java SetOptions back to C++ SetOptions since // there is no public API that returns a SetOptions yet. private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_SET_OPTIONS_ANDROID_H_ <file_sep>#include "firestore/src/android/collection_reference_android.h" #include <string> #include <utility> #include "app/src/util_android.h" #include "firestore/src/android/document_reference_android.h" #include "firestore/src/android/field_value_android.h" #include "firestore/src/android/promise_android.h" #include "firestore/src/android/util_android.h" namespace firebase { namespace firestore { // clang-format off #define COLLECTION_REFERENCE_METHODS(X) \ X(GetId, "getId", "()Ljava/lang/String;"), \ X(GetPath, "getPath", "()Ljava/lang/String;"), \ X(GetParent, "getParent", \ "()Lcom/google/firebase/firestore/DocumentReference;"), \ X(DocumentAutoId, "document", \ "()Lcom/google/firebase/firestore/DocumentReference;"), \ X(Document, "document", "(Ljava/lang/String;)" \ "Lcom/google/firebase/firestore/DocumentReference;"), \ X(Add, "add", \ "(Ljava/lang/Object;)Lcom/google/android/gms/tasks/Task;") // clang-format on METHOD_LOOKUP_DECLARATION(collection_reference, COLLECTION_REFERENCE_METHODS) METHOD_LOOKUP_DEFINITION(collection_reference, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/CollectionReference", COLLECTION_REFERENCE_METHODS) const std::string& CollectionReferenceInternal::id() const { if (!cached_id_.empty()) { return cached_id_; } JNIEnv* env = firestore_->app()->GetJNIEnv(); jstring id = static_cast<jstring>(env->CallObjectMethod( obj_, collection_reference::GetMethodId(collection_reference::kGetId))); cached_id_ = util::JniStringToString(env, id); CheckAndClearJniExceptions(env); return cached_id_; } const std::string& CollectionReferenceInternal::path() const { if (!cached_path_.empty()) { return cached_path_; } JNIEnv* env = firestore_->app()->GetJNIEnv(); jstring path = static_cast<jstring>(env->CallObjectMethod( obj_, collection_reference::GetMethodId(collection_reference::kGetPath))); cached_path_ = util::JniStringToString(env, path); CheckAndClearJniExceptions(env); return cached_path_; } DocumentReference CollectionReferenceInternal::Parent() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject parent = env->CallObjectMethod( obj_, collection_reference::GetMethodId(collection_reference::kGetParent)); CheckAndClearJniExceptions(env); if (parent == nullptr) { return DocumentReference(); } else { DocumentReferenceInternal* internal = new DocumentReferenceInternal{firestore_, parent}; env->DeleteLocalRef(parent); return DocumentReference(internal); } } DocumentReference CollectionReferenceInternal::Document() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject document = env->CallObjectMethod( obj_, collection_reference::GetMethodId(collection_reference::kDocumentAutoId)); DocumentReferenceInternal* internal = new DocumentReferenceInternal{firestore_, document}; env->DeleteLocalRef(document); CheckAndClearJniExceptions(env); return DocumentReference(internal); } DocumentReference CollectionReferenceInternal::Document( const std::string& document_path) const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jstring path_string = env->NewStringUTF(document_path.c_str()); jobject document = env->CallObjectMethod( obj_, collection_reference::GetMethodId(collection_reference::kDocument), path_string); env->DeleteLocalRef(path_string); CheckAndClearJniExceptions(env); DocumentReferenceInternal* internal = new DocumentReferenceInternal{firestore_, document}; env->DeleteLocalRef(document); CheckAndClearJniExceptions(env); return DocumentReference(internal); } Future<DocumentReference> CollectionReferenceInternal::Add( const MapFieldValue& data) { FieldValueInternal map_value(data); JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject task = env->CallObjectMethod( obj_, collection_reference::GetMethodId(collection_reference::kAdd), map_value.java_object()); CheckAndClearJniExceptions(env); auto promise = MakePromise<DocumentReference, DocumentReferenceInternal>(); promise.RegisterForTask(CollectionReferenceFn::kAdd, task); env->DeleteLocalRef(task); CheckAndClearJniExceptions(env); return promise.GetFuture(); } Future<DocumentReference> CollectionReferenceInternal::AddLastResult() { return LastResult<DocumentReference>(CollectionReferenceFn::kAdd); } /* static */ bool CollectionReferenceInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = collection_reference::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void CollectionReferenceInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); collection_reference::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>#include "firestore/src/common/util.h" namespace firebase { namespace firestore { const std::string& EmptyString() { static const std::string kEmptyString; return kEmptyString; } } // namespace firestore } // namespace firebase <file_sep>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef FIREBASE_REMOTE_CONFIG_CLIENT_CPP_SRC_DESKTOP_REST_NANOPB_H_ #define FIREBASE_REMOTE_CONFIG_CLIENT_CPP_SRC_DESKTOP_REST_NANOPB_H_ // This isn't strictly necessary, however the generated names from the protos // are very long. This macro generates a few short aliases to variables present // in the generated files based on the name passed in. It also makes the names // more idiomatic for constants. #define NPB_ALIAS_DEF(name, longname) \ using name = longname; \ const name kDefault##name = longname##_init_default; \ const pb_field_t* const k##name##Fields = longname##_fields; #endif // FIREBASE_REMOTE_CONFIG_CLIENT_CPP_SRC_DESKTOP_REST_NANOPB_H_ <file_sep>// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef FIREBASE_INSTANCE_ID_CLIENT_CPP_SRC_INSTANCE_ID_INTERNAL_BASE_H_ #define FIREBASE_INSTANCE_ID_CLIENT_CPP_SRC_INSTANCE_ID_INTERNAL_BASE_H_ #include <map> #include "app/src/mutex.h" #include "app/src/reference_counted_future_impl.h" #include "app/src/util.h" #include "instance_id/src/include/firebase/instance_id.h" namespace firebase { namespace instance_id { namespace internal { // Common functionality for platform implementations of InstanceIdInternal. class InstanceIdInternalBase { public: // Enumeration for API functions that return a Future. // This allows us to hold a Future for the most recent call to that API. enum ApiFunction { kApiFunctionGetId = 0, kApiFunctionDeleteId, kApiFunctionGetToken, kApiFunctionDeleteToken, kApiFunctionMax, }; public: InstanceIdInternalBase(); ~InstanceIdInternalBase(); // Allocate a future handle for the specified function. template <typename T> SafeFutureHandle<T> FutureAlloc(ApiFunction function_index) { return future_api_.SafeAlloc<T>(function_index); } // Get the future API implementation. ReferenceCountedFutureImpl &future_api() { return future_api_; } // Associate an InstanceId instance with an app. static void RegisterInstanceIdForApp(App *app, InstanceId *instance_id); // Remove association of InstanceId instance with an App. static void UnregisterInstanceIdForApp(App *app, InstanceId *instance_id); // Find an InstanceId instance associated with an app. static InstanceId *FindInstanceIdByApp(App *app); // Return the mutex to make sure both find and register are guarded. static Mutex& mutex() { return instance_id_by_app_mutex_; } private: /// Handle calls from Futures that the API returns. ReferenceCountedFutureImpl future_api_; /// Identifier used to track futures associated with future_impl. std::string future_api_id_; static std::map<App *, InstanceId *> instance_id_by_app_; static Mutex instance_id_by_app_mutex_; }; } // namespace internal } // namespace instance_id } // namespace firebase #endif // FIREBASE_INSTANCE_ID_CLIENT_CPP_SRC_INSTANCE_ID_INTERNAL_BASE_H_ <file_sep>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef FIREBASE_REMOTE_CONFIG_CLIENT_CPP_SRC_DESKTOP_REST_NANOPB_ENCODE_H_ #define FIREBASE_REMOTE_CONFIG_CLIENT_CPP_SRC_DESKTOP_REST_NANOPB_ENCODE_H_ #include <map> #include <string> namespace firebase { namespace remote_config { namespace internal { typedef std::map<std::string, std::string> NamedValues; struct PackageData { // name of the package for which the device is fetching config from the // backend. std::string package_name; // Firebase Project Number. std::string gmp_project_id; // per namespace digests of the local config table of the app, in // the format of: NamedValue(name=namespace, value=digest) NamedValues namespace_digest; // custom variables as defined by the client app. NamedValues custom_variable; // optional // The instance id of the app. std::string app_instance_id; // optional // The instance id token of the app. std::string app_instance_id_token; // version of the firebase remote config sdk. constructed by a major version, // a minor version, and a patch version, using the formula: // (major * 10000) + (minor * 100) + patch int sdk_version; // the cache expiration seconds specified while calling fetch() // in seconds int requested_cache_expiration_seconds; // the age of the fetched config: now() - last time fetch() was called // in seconds // if there was no fetched config, the value will be set to -1 int fetched_config_age_seconds; // the age of the active config: // now() - last time activateFetched() was called // in seconds // if there was no active config, the value will be set to -1 int active_config_age_seconds; }; struct ConfigFetchRequest { int client_version; int device_type; int device_subtype; PackageData package_data; }; std::string EncodeFetchRequest(const ConfigFetchRequest& config_fetch_request); } // namespace internal } // namespace remote_config } // namespace firebase #endif // FIREBASE_REMOTE_CONFIG_CLIENT_CPP_SRC_DESKTOP_REST_NANOPB_ENCODE_H_ <file_sep>#include "firestore/src/android/query_android.h" #include "app/meta/move.h" #include "app/src/assert.h" #include "firestore/src/android/direction_android.h" #include "firestore/src/android/document_snapshot_android.h" #include "firestore/src/android/event_listener_android.h" #include "firestore/src/android/field_path_android.h" #include "firestore/src/android/field_value_android.h" #include "firestore/src/android/firestore_android.h" #include "firestore/src/android/lambda_event_listener.h" #include "firestore/src/android/metadata_changes_android.h" #include "firestore/src/android/promise_android.h" #include "firestore/src/android/source_android.h" #include "firestore/src/android/util_android.h" #include "firestore/src/include/firebase/firestore.h" namespace firebase { namespace firestore { METHOD_LOOKUP_DEFINITION(query, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/Query", QUERY_METHODS) Firestore* QueryInternal::firestore() { FIREBASE_ASSERT(firestore_->firestore_public() != nullptr); return firestore_->firestore_public(); } Query QueryInternal::OrderBy(const FieldPath& field, Query::Direction direction) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject j_field = FieldPathConverter::ToJavaObject(env, field); jobject j_direction = DirectionInternal::ToJavaObject(env, direction); jobject query = env->CallObjectMethod( obj_, query::GetMethodId(query::kOrderBy), j_field, j_direction); CheckAndClearJniExceptions(env); QueryInternal* internal = new QueryInternal{firestore_, query}; env->DeleteLocalRef(j_field); env->DeleteLocalRef(query); CheckAndClearJniExceptions(env); return Query{internal}; } Query QueryInternal::Limit(int32_t limit) { JNIEnv* env = firestore_->app()->GetJNIEnv(); // Although the backend supports signed int32, Android client SDK uses long // as parameter type. So we cast it to jlong instead of jint here. jobject query = env->CallObjectMethod(obj_, query::GetMethodId(query::kLimit), static_cast<jlong>(limit)); CheckAndClearJniExceptions(env); QueryInternal* internal = new QueryInternal{firestore_, query}; env->DeleteLocalRef(query); CheckAndClearJniExceptions(env); return Query{internal}; } Query QueryInternal::LimitToLast(int32_t limit) { JNIEnv* env = firestore_->app()->GetJNIEnv(); // Although the backend supports signed int32, Android client SDK uses long // as parameter type. So we cast it to jlong instead of jint here. jobject query = env->CallObjectMethod( obj_, query::GetMethodId(query::kLimitToLast), static_cast<jlong>(limit)); CheckAndClearJniExceptions(env); QueryInternal* internal = new QueryInternal{firestore_, query}; env->DeleteLocalRef(query); CheckAndClearJniExceptions(env); return Query{internal}; } Future<QuerySnapshot> QueryInternal::Get(Source source) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject task = env->CallObjectMethod(obj_, query::GetMethodId(query::kGet), SourceInternal::ToJavaObject(env, source)); CheckAndClearJniExceptions(env); auto promise = MakePromise<QuerySnapshot, QuerySnapshotInternal>(); promise.RegisterForTask(QueryFn::kGet, task); env->DeleteLocalRef(task); CheckAndClearJniExceptions(env); return promise.GetFuture(); } Future<QuerySnapshot> QueryInternal::GetLastResult() { return LastResult<QuerySnapshot>(QueryFn::kGet); } /* static */ bool QueryInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = query::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void QueryInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); query::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } Query QueryInternal::Where(const FieldPath& field, query::Method method, const FieldValue& value) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject path = FieldPathConverter::ToJavaObject(env, field); jobject query = env->CallObjectMethod(obj_, query::GetMethodId(method), path, value.internal_->java_object()); CheckAndClearJniExceptions(env); QueryInternal* internal = new QueryInternal{firestore_, query}; env->DeleteLocalRef(path); env->DeleteLocalRef(query); CheckAndClearJniExceptions(env); return Query{internal}; } Query QueryInternal::Where(const FieldPath& field, query::Method method, const std::vector<FieldValue>& values) { JNIEnv* env = firestore_->app()->GetJNIEnv(); // Convert std::vector into java.util.List object. // TODO(chenbrian): Refactor this into a helper function. jobject converted_values = env->NewObject( util::array_list::GetClass(), util::array_list::GetMethodId(util::array_list::kConstructor)); jmethodID add_method = util::array_list::GetMethodId(util::array_list::kAdd); jsize size = static_cast<jsize>(values.size()); for (jsize i = 0; i < size; ++i) { // ArrayList.Add() always returns true, which we have no use for. env->CallBooleanMethod(converted_values, add_method, values[i].internal_->java_object()); CheckAndClearJniExceptions(env); } jobject path = FieldPathConverter::ToJavaObject(env, field); jobject query = env->CallObjectMethod(obj_, query::GetMethodId(method), path, converted_values); CheckAndClearJniExceptions(env); QueryInternal* internal = new QueryInternal{firestore_, query}; env->DeleteLocalRef(path); env->DeleteLocalRef(query); env->DeleteLocalRef(converted_values); return Query{internal}; } Query QueryInternal::WithBound(query::Method method, const DocumentSnapshot& snapshot) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject query = env->CallObjectMethod(obj_, query::GetMethodId(method), snapshot.internal_->java_object()); CheckAndClearJniExceptions(env); QueryInternal* internal = new QueryInternal{firestore_, query}; env->DeleteLocalRef(query); CheckAndClearJniExceptions(env); return Query{internal}; } Query QueryInternal::WithBound(query::Method method, const std::vector<FieldValue>& values) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobjectArray converted_values = ConvertFieldValues(env, values); jobject query = env->CallObjectMethod(obj_, query::GetMethodId(method), converted_values); CheckAndClearJniExceptions(env); env->DeleteLocalRef(converted_values); QueryInternal* internal = new QueryInternal{firestore_, query}; env->DeleteLocalRef(query); CheckAndClearJniExceptions(env); return Query{internal}; } #if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) ListenerRegistration QueryInternal::AddSnapshotListener( MetadataChanges metadata_changes, std::function<void(const QuerySnapshot&, Error)> callback) { LambdaEventListener<QuerySnapshot>* listener = new LambdaEventListener<QuerySnapshot>(firebase::Move(callback)); return AddSnapshotListener(metadata_changes, listener, /*passing_listener_ownership=*/true); } #endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) ListenerRegistration QueryInternal::AddSnapshotListener( MetadataChanges metadata_changes, EventListener<QuerySnapshot>* listener, bool passing_listener_ownership) { JNIEnv* env = firestore_->app()->GetJNIEnv(); // Create listener. jobject java_listener = EventListenerInternal::EventListenerToJavaEventListener(env, firestore_, listener); jobject java_metadata = MetadataChangesInternal::ToJavaObject(env, metadata_changes); // Register listener. jobject java_registration = env->CallObjectMethod( obj_, query::GetMethodId(query::kAddSnapshotListener), java_metadata, java_listener); env->DeleteLocalRef(java_listener); CheckAndClearJniExceptions(env); // Wrapping ListenerRegistrationInternal* registration = new ListenerRegistrationInternal{ firestore_, listener, passing_listener_ownership, java_registration}; env->DeleteLocalRef(java_registration); return ListenerRegistration{registration}; } jobjectArray QueryInternal::ConvertFieldValues( JNIEnv* env, const std::vector<FieldValue>& field_values) { jsize size = static_cast<jsize>(field_values.size()); jobjectArray result = env->NewObjectArray(size, util::object::GetClass(), /*initialElement=*/nullptr); for (jsize i = 0; i < size; ++i) { env->SetObjectArrayElement(result, i, field_values[i].internal_->java_object()); } return result; } bool operator==(const QueryInternal& lhs, const QueryInternal& rhs) { return lhs.EqualsJavaObject(rhs); } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_VECTOR_HELPER_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_VECTOR_HELPER_H_ #include "app/meta/move.h" #include "firebase/firestore/document_change.h" #include "firebase/firestore/document_snapshot.h" #include "firebase/firestore/field_path.h" #include "firebase/firestore/field_value.h" namespace firebase { namespace firestore { namespace csharp { // FieldValue is converted to FieldValueInternal of internal access, which makes // it impossible to convert std::vector<FieldValue> with std_vector.i. Instead // of making a fully working std::vector<FieldValue>, we defined a few function // here. // We cannot call std::vector<FieldValue>::foo() in C# since it is not exposed // via the .dll interface as SWIG cannot convert it. Here we essentially define // a function, which SWIG can convert and thus expose it via the .dll. So C# // code can call it. inline std::size_t vector_size(const std::vector<FieldValue>& self) { return self.size(); } inline const FieldValue& vector_get(const std::vector<FieldValue>& self, std::size_t index) { return self[index]; } inline std::vector<FieldValue> vector_fv_create(std::size_t size) { std::vector<FieldValue> result(size); return result; } // This is the only way to make it efficient for non-STLPort and also // STLPort-compatible. inline void vector_set(std::vector<FieldValue>* self, std::size_t index, FieldValue field_value) { // This could be either a move-assignment or a normal assignment. (*self)[index] = firebase::Move(field_value); } // Similarly, DocumentSnapshot is converted to DocumentSnapshotInternal and we // defined a few helper function to deal with std::vector<DocumentSnapshot>. inline const DocumentSnapshot& vector_get( const std::vector<DocumentSnapshot>& self, std::size_t index) { return self[index]; } // Similarly, DocumentChange is converted to DocumentChangeInternal and we // defined a few helper function to deal with std::vector<DocumentChange>. inline std::size_t vector_size( const std::vector<DocumentChange>& self){ return self.size(); } inline const DocumentChange& vector_get( const std::vector<DocumentChange>& self, std::size_t index) { return self[index]; } // Similarly, FieldPath is converted to FieldPathInternal and we defined a few // helper function to deal with std::vector<FieldPath>. inline std::vector<FieldPath> vector_fp_create() { return std::vector<FieldPath>{}; } inline void vector_push_back(std::vector<FieldPath>* self, FieldPath field_path) { self->push_back(firebase::Move(field_path)); } } // namespace csharp } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_VECTOR_HELPER_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_UTIL_IOS_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_UTIL_IOS_H_ #include "firestore/src/include/firebase/firestore.h" #include "firestore/src/ios/firestore_ios.h" #include "Firestore/core/src/firebase/firestore/api/firestore.h" namespace firebase { namespace firestore { template <typename T> FirestoreInternal* GetFirestoreInternal(T* object) { void* raw_ptr = object->firestore()->extension(); return static_cast<FirestoreInternal*>(raw_ptr); } template <typename T> Firestore* GetFirestore(T* object) { return GetFirestoreInternal(object)->firestore_public(); } } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_UTIL_IOS_H_ <file_sep>// Copyright 2016 Google Inc. All Rights Reserved. #include "firestore/src/android/firestore_android.h" #include "app/meta/move.h" #include "app/src/assert.h" #include "app/src/embedded_file.h" #include "app/src/include/firebase/future.h" #include "app/src/reference_counted_future_impl.h" #include "app/src/util_android.h" #include "firestore/firestore_resources.h" #include "firestore/src/android/blob_android.h" #include "firestore/src/android/collection_reference_android.h" #include "firestore/src/android/direction_android.h" #include "firestore/src/android/document_change_android.h" #include "firestore/src/android/document_change_type_android.h" #include "firestore/src/android/document_reference_android.h" #include "firestore/src/android/document_snapshot_android.h" #include "firestore/src/android/event_listener_android.h" #include "firestore/src/android/field_path_android.h" #include "firestore/src/android/field_value_android.h" #include "firestore/src/android/firebase_firestore_exception_android.h" #include "firestore/src/android/firebase_firestore_settings_android.h" #include "firestore/src/android/geo_point_android.h" #include "firestore/src/android/lambda_event_listener.h" #include "firestore/src/android/lambda_transaction_function.h" #include "firestore/src/android/metadata_changes_android.h" #include "firestore/src/android/promise_android.h" #include "firestore/src/android/query_android.h" #include "firestore/src/android/query_snapshot_android.h" #include "firestore/src/android/server_timestamp_behavior_android.h" #include "firestore/src/android/set_options_android.h" #include "firestore/src/android/snapshot_metadata_android.h" #include "firestore/src/android/source_android.h" #include "firestore/src/android/timestamp_android.h" #include "firestore/src/android/transaction_android.h" #include "firestore/src/android/util_android.h" #include "firestore/src/android/wrapper.h" #include "firestore/src/android/write_batch_android.h" #include "firestore/src/include/firebase/firestore.h" namespace firebase { namespace firestore { const char kApiIdentifier[] = "Firestore"; // clang-format off #define FIREBASE_FIRESTORE_METHODS(X) \ X(Collection, "collection", \ "(Ljava/lang/String;)" \ "Lcom/google/firebase/firestore/CollectionReference;"), \ X(Document, "document", \ "(Ljava/lang/String;)" \ "Lcom/google/firebase/firestore/DocumentReference;"), \ X(CollectionGroup, "collectionGroup", \ "(Ljava/lang/String;)" \ "Lcom/google/firebase/firestore/Query;"), \ X(GetSettings, "getFirestoreSettings", \ "()Lcom/google/firebase/firestore/FirebaseFirestoreSettings;"), \ X(GetInstance, "getInstance", \ "(Lcom/google/firebase/FirebaseApp;)" \ "Lcom/google/firebase/firestore/FirebaseFirestore;", \ util::kMethodTypeStatic), \ X(SetLoggingEnabled, "setLoggingEnabled", \ "(Z)V", util::kMethodTypeStatic), \ X(SetSettings, "setFirestoreSettings", \ "(Lcom/google/firebase/firestore/FirebaseFirestoreSettings;)V"), \ X(Batch, "batch", \ "()Lcom/google/firebase/firestore/WriteBatch;"), \ X(RunTransaction, "runTransaction", \ "(Lcom/google/firebase/firestore/Transaction$Function;)" \ "Lcom/google/android/gms/tasks/Task;"), \ X(EnableNetwork, "enableNetwork", \ "()Lcom/google/android/gms/tasks/Task;"), \ X(DisableNetwork, "disableNetwork", \ "()Lcom/google/android/gms/tasks/Task;"), \ X(Terminate, "terminate", \ "()Lcom/google/android/gms/tasks/Task;"), \ X(WaitForPendingWrites, "waitForPendingWrites", \ "()Lcom/google/android/gms/tasks/Task;"), \ X(ClearPersistence, "clearPersistence", \ "()Lcom/google/android/gms/tasks/Task;"), \ X(AddSnapshotsInSyncListener, "addSnapshotsInSyncListener", \ "(Ljava/lang/Runnable;)" \ "Lcom/google/firebase/firestore/ListenerRegistration;") // clang-format on METHOD_LOOKUP_DECLARATION(firebase_firestore, FIREBASE_FIRESTORE_METHODS) METHOD_LOOKUP_DEFINITION(firebase_firestore, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/FirebaseFirestore", FIREBASE_FIRESTORE_METHODS) Mutex FirestoreInternal::init_mutex_; // NOLINT int FirestoreInternal::initialize_count_ = 0; FirestoreInternal::FirestoreInternal(App* app) { FIREBASE_ASSERT(app != nullptr); if (!Initialize(app)) return; app_ = app; JNIEnv* env = app_->GetJNIEnv(); jobject platform_app = app_->GetPlatformApp(); jobject firestore_obj = env->CallStaticObjectMethod( firebase_firestore::GetClass(), firebase_firestore::GetMethodId(firebase_firestore::kGetInstance), platform_app); util::CheckAndClearJniExceptions(env); env->DeleteLocalRef(platform_app); FIREBASE_ASSERT(firestore_obj != nullptr); obj_ = env->NewGlobalRef(firestore_obj); env->DeleteLocalRef(firestore_obj); // Mainly for enabling TimestampsInSnapshotsEnabled. The rest comes from the // default in native SDK. The C++ implementation relies on that for reading // timestamp FieldValues correctly. TODO(zxu): Once it is set to true by // default, we may safely remove the calls below. Settings setting = settings(); set_settings(setting); future_manager_.AllocFutureApi(this, static_cast<int>(FirestoreFn::kCount)); } /* static */ bool FirestoreInternal::Initialize(App* app) { MutexLock init_lock(init_mutex_); if (initialize_count_ == 0) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); if (!(firebase_firestore::CacheMethodIds(env, activity) && // Call Initialize on each Firestore internal class. BlobInternal::Initialize(app) && CollectionReferenceInternal::Initialize(app) && DirectionInternal::Initialize(app) && DocumentChangeInternal::Initialize(app) && DocumentChangeTypeInternal::Initialize(app) && DocumentReferenceInternal::Initialize(app) && DocumentSnapshotInternal::Initialize(app) && FieldPathConverter::Initialize(app) && FieldValueInternal::Initialize(app) && FirebaseFirestoreExceptionInternal::Initialize(app) && FirebaseFirestoreSettingsInternal::Initialize(app) && GeoPointInternal::Initialize(app) && ListenerRegistrationInternal::Initialize(app) && MetadataChangesInternal::Initialize(app) && QueryInternal::Initialize(app) && QuerySnapshotInternal::Initialize(app) && ServerTimestampBehaviorInternal::Initialize(app) && SetOptionsInternal::Initialize(app) && SnapshotMetadataInternal::Initialize(app) && SourceInternal::Initialize(app) && TimestampInternal::Initialize(app) && TransactionInternal::Initialize(app) && Wrapper::Initialize(app) && WriteBatchInternal::Initialize(app) && // Initialize those embedded Firestore internal classes. InitializeEmbeddedClasses(app))) { ReleaseClasses(app); return false; } util::CheckAndClearJniExceptions(env); } initialize_count_++; return true; } /* static */ bool FirestoreInternal::InitializeEmbeddedClasses(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); // Terminate() handles tearing this down. // Load embedded classes. const std::vector<internal::EmbeddedFile> embedded_files = util::CacheEmbeddedFiles( env, activity, internal::EmbeddedFile::ToVector( ::firebase_firestore::firestore_resources_filename, ::firebase_firestore::firestore_resources_data, ::firebase_firestore::firestore_resources_size)); return EventListenerInternal::InitializeEmbeddedClasses(app, &embedded_files) && TransactionInternal::InitializeEmbeddedClasses(app, &embedded_files); } /* static */ void FirestoreInternal::ReleaseClasses(App* app) { JNIEnv* env = app->GetJNIEnv(); firebase_firestore::ReleaseClass(env); util::CheckAndClearJniExceptions(env); // Call Terminate on each Firestore internal class. BlobInternal::Terminate(app); CollectionReferenceInternal::Terminate(app); DirectionInternal::Terminate(app); DocumentChangeInternal::Terminate(app); DocumentChangeTypeInternal::Terminate(app); DocumentReferenceInternal::Terminate(app); DocumentSnapshotInternal::Terminate(app); EventListenerInternal::Terminate(app); FieldPathConverter::Terminate(app); FieldValueInternal::Terminate(app); FirebaseFirestoreExceptionInternal::Terminate(app); FirebaseFirestoreSettingsInternal::Terminate(app); GeoPointInternal::Terminate(app); ListenerRegistrationInternal::Terminate(app); MetadataChangesInternal::Terminate(app); QueryInternal::Terminate(app); QuerySnapshotInternal::Terminate(app); ServerTimestampBehaviorInternal::Terminate(app); SetOptionsInternal::Terminate(app); SnapshotMetadataInternal::Terminate(app); SourceInternal::Terminate(app); TimestampInternal::Terminate(app); TransactionInternal::Terminate(app); Wrapper::Terminate(app); WriteBatchInternal::Terminate(app); } /* static */ void FirestoreInternal::Terminate(App* app) { MutexLock init_lock(init_mutex_); FIREBASE_ASSERT(initialize_count_ > 0); initialize_count_--; if (initialize_count_ == 0) { ReleaseClasses(app); } } FirestoreInternal::~FirestoreInternal() { // If initialization failed, there is nothing to clean up. if (app_ == nullptr) return; { MutexLock lock(listener_registration_mutex_); // TODO(varconst): investigate why not all listener registrations are // cleared. // FIREBASE_ASSERT(listener_registrations_.empty()); for (auto* reg : listener_registrations_) { delete reg; } listener_registrations_.clear(); } future_manager_.ReleaseFutureApi(this); JNIEnv* env = app_->GetJNIEnv(); env->DeleteGlobalRef(obj_); obj_ = nullptr; Terminate(app_); app_ = nullptr; util::CheckAndClearJniExceptions(env); } CollectionReference FirestoreInternal::Collection( const char* collection_path) const { JNIEnv* env = app_->GetJNIEnv(); jstring path_string = env->NewStringUTF(collection_path); jobject collection_reference = env->CallObjectMethod( obj_, firebase_firestore::GetMethodId(firebase_firestore::kCollection), path_string); env->DeleteLocalRef(path_string); CheckAndClearJniExceptions(env); FIREBASE_ASSERT(collection_reference != nullptr); CollectionReferenceInternal* internal = new CollectionReferenceInternal{ const_cast<FirestoreInternal*>(this), collection_reference}; env->DeleteLocalRef(collection_reference); CheckAndClearJniExceptions(env); return CollectionReference{internal}; } DocumentReference FirestoreInternal::Document(const char* document_path) const { JNIEnv* env = app_->GetJNIEnv(); jstring path_string = env->NewStringUTF(document_path); jobject document_reference = env->CallObjectMethod( obj_, firebase_firestore::GetMethodId(firebase_firestore::kDocument), path_string); env->DeleteLocalRef(path_string); CheckAndClearJniExceptions(env); FIREBASE_ASSERT(document_reference != nullptr); DocumentReferenceInternal* internal = new DocumentReferenceInternal{ const_cast<FirestoreInternal*>(this), document_reference}; env->DeleteLocalRef(document_reference); CheckAndClearJniExceptions(env); return DocumentReference{internal}; } Query FirestoreInternal::CollectionGroup(const char* collection_id) const { JNIEnv* env = app_->GetJNIEnv(); jstring collection_id_string = env->NewStringUTF(collection_id); jobject query = env->CallObjectMethod( obj_, firebase_firestore::GetMethodId(firebase_firestore::kCollectionGroup), collection_id_string); env->DeleteLocalRef(collection_id_string); CheckAndClearJniExceptions(env); FIREBASE_ASSERT(query != nullptr); QueryInternal* internal = new QueryInternal{const_cast<FirestoreInternal*>(this), query}; env->DeleteLocalRef(query); CheckAndClearJniExceptions(env); return Query{internal}; } Settings FirestoreInternal::settings() const { JNIEnv* env = app_->GetJNIEnv(); jobject settings = env->CallObjectMethod( obj_, firebase_firestore::GetMethodId(firebase_firestore::kGetSettings)); FIREBASE_ASSERT(settings != nullptr); Settings result = FirebaseFirestoreSettingsInternal::JavaSettingToSetting(env, settings); env->DeleteLocalRef(settings); CheckAndClearJniExceptions(env); return result; } void FirestoreInternal::set_settings(const Settings& settings) { JNIEnv* env = app_->GetJNIEnv(); jobject settings_jobj = FirebaseFirestoreSettingsInternal::SettingToJavaSetting(env, settings); env->CallVoidMethod( obj_, firebase_firestore::GetMethodId(firebase_firestore::kSetSettings), settings_jobj); env->DeleteLocalRef(settings_jobj); CheckAndClearJniExceptions(env); } WriteBatch FirestoreInternal::batch() const { JNIEnv* env = app_->GetJNIEnv(); jobject write_batch = env->CallObjectMethod( obj_, firebase_firestore::GetMethodId(firebase_firestore::kBatch)); FIREBASE_ASSERT(write_batch != nullptr); WriteBatchInternal* internal = new WriteBatchInternal{const_cast<FirestoreInternal*>(this), write_batch}; env->DeleteLocalRef(write_batch); CheckAndClearJniExceptions(env); return WriteBatch{internal}; } Future<void> FirestoreInternal::RunTransaction(TransactionFunction* update, bool is_lambda) { JNIEnv* env = app_->GetJNIEnv(); jobject transaction_function = TransactionInternal::ToJavaObject(env, this, update); jobject task = env->CallObjectMethod( obj_, firebase_firestore::GetMethodId(firebase_firestore::kRunTransaction), transaction_function); env->DeleteLocalRef(transaction_function); CheckAndClearJniExceptions(env); #if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) auto* completion = static_cast<LambdaTransactionFunction*>(is_lambda ? update : nullptr); Promise<void, void, FirestoreFn> promise{ref_future(), this, completion}; #else // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) Promise<void, void, FirestoreFn> promise{ref_future(), this}; #endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) promise.RegisterForTask(FirestoreFn::kRunTransaction, task); env->DeleteLocalRef(task); CheckAndClearJniExceptions(env); return promise.GetFuture(); } #if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) Future<void> FirestoreInternal::RunTransaction( std::function<Error(Transaction*, std::string*)> update) { LambdaTransactionFunction* lambda_update = new LambdaTransactionFunction(firebase::Move(update)); return RunTransaction(lambda_update, /*is_lambda=*/true); } #endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) Future<void> FirestoreInternal::RunTransactionLastResult() { return LastResult(FirestoreFn::kRunTransaction); } Future<void> FirestoreInternal::DisableNetwork() { JNIEnv* env = app_->GetJNIEnv(); jobject task = env->CallObjectMethod( obj_, firebase_firestore::GetMethodId(firebase_firestore::kDisableNetwork)); CheckAndClearJniExceptions(env); Promise<void, void, FirestoreFn> promise{ref_future(), this}; promise.RegisterForTask(FirestoreFn::kDisableNetwork, task); env->DeleteLocalRef(task); CheckAndClearJniExceptions(env); return promise.GetFuture(); } Future<void> FirestoreInternal::DisableNetworkLastResult() { return LastResult(FirestoreFn::kDisableNetwork); } Future<void> FirestoreInternal::EnableNetwork() { JNIEnv* env = app_->GetJNIEnv(); jobject task = env->CallObjectMethod( obj_, firebase_firestore::GetMethodId(firebase_firestore::kEnableNetwork)); CheckAndClearJniExceptions(env); Promise<void, void, FirestoreFn> promise{ref_future(), this}; promise.RegisterForTask(FirestoreFn::kEnableNetwork, task); env->DeleteLocalRef(task); CheckAndClearJniExceptions(env); return promise.GetFuture(); } Future<void> FirestoreInternal::EnableNetworkLastResult() { return LastResult(FirestoreFn::kEnableNetwork); } Future<void> FirestoreInternal::Terminate() { JNIEnv* env = app_->GetJNIEnv(); jobject task = env->CallObjectMethod( obj_, firebase_firestore::GetMethodId(firebase_firestore::kTerminate)); CheckAndClearJniExceptions(env); Promise<void, void, FirestoreFn> promise{ref_future(), this}; promise.RegisterForTask(FirestoreFn::kTerminate, task); env->DeleteLocalRef(task); CheckAndClearJniExceptions(env); return promise.GetFuture(); } Future<void> FirestoreInternal::TerminateLastResult() { return LastResult(FirestoreFn::kTerminate); } Future<void> FirestoreInternal::WaitForPendingWrites() { JNIEnv* env = app_->GetJNIEnv(); jobject task = env->CallObjectMethod( obj_, firebase_firestore::GetMethodId( firebase_firestore::kWaitForPendingWrites)); CheckAndClearJniExceptions(env); Promise<void, void, FirestoreFn> promise{ref_future(), this}; promise.RegisterForTask(FirestoreFn::kWaitForPendingWrites, task); env->DeleteLocalRef(task); CheckAndClearJniExceptions(env); return promise.GetFuture(); } Future<void> FirestoreInternal::WaitForPendingWritesLastResult() { return LastResult(FirestoreFn::kWaitForPendingWrites); } Future<void> FirestoreInternal::ClearPersistence() { JNIEnv* env = app_->GetJNIEnv(); jobject task = env->CallObjectMethod( obj_, firebase_firestore::GetMethodId(firebase_firestore::kClearPersistence)); CheckAndClearJniExceptions(env); Promise<void, void, FirestoreFn> promise{ref_future(), this}; promise.RegisterForTask(FirestoreFn::kClearPersistence, task); env->DeleteLocalRef(task); CheckAndClearJniExceptions(env); return promise.GetFuture(); } Future<void> FirestoreInternal::ClearPersistenceLastResult() { return LastResult(FirestoreFn::kClearPersistence); } ListenerRegistration FirestoreInternal::AddSnapshotsInSyncListener( EventListener<void>* listener, bool passing_listener_ownership) { JNIEnv* env = app_->GetJNIEnv(); // Create listener. jobject java_runnable = EventListenerInternal::EventListenerToJavaRunnable(env, listener); // Register listener. jobject java_registration = env->CallObjectMethod( obj_, firebase_firestore::GetMethodId( firebase_firestore::kAddSnapshotsInSyncListener), java_runnable); env->DeleteLocalRef(java_runnable); CheckAndClearJniExceptions(env); // Wrapping ListenerRegistrationInternal* registration = new ListenerRegistrationInternal{ this, listener, passing_listener_ownership, java_registration}; env->DeleteLocalRef(java_registration); return ListenerRegistration{registration}; } #if defined(FIREBASE_USE_STD_FUNCTION) ListenerRegistration FirestoreInternal::AddSnapshotsInSyncListener( std::function<void()> callback) { auto* listener = new LambdaEventListener<void>(firebase::Move(callback)); return AddSnapshotsInSyncListener(listener, /*passing_listener_ownership=*/true); } #endif // defined(FIREBASE_USE_STD_FUNCTION) void FirestoreInternal::RegisterListenerRegistration( ListenerRegistrationInternal* registration) { MutexLock lock(listener_registration_mutex_); listener_registrations_.insert(registration); } void FirestoreInternal::UnregisterListenerRegistration( ListenerRegistrationInternal* registration) { MutexLock lock(listener_registration_mutex_); auto iter = listener_registrations_.find(registration); if (iter != listener_registrations_.end()) { delete *iter; listener_registrations_.erase(iter); } } /* static */ void Firestore::set_logging_enabled(bool logging_enabled) { JNIEnv* env = firebase::util::GetJNIEnvFromApp(); env->CallStaticVoidMethod( firebase_firestore::GetClass(), firebase_firestore::GetMethodId(firebase_firestore::kSetLoggingEnabled), logging_enabled); CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>#include "firestore/src/android/query_snapshot_android.h" #include <jni.h> #include "app/src/assert.h" #include "app/src/util_android.h" #include "firestore/src/android/document_change_android.h" #include "firestore/src/android/document_snapshot_android.h" #include "firestore/src/android/metadata_changes_android.h" #include "firestore/src/android/query_android.h" #include "firestore/src/android/snapshot_metadata_android.h" #include "firestore/src/android/util_android.h" namespace firebase { namespace firestore { // clang-format off #define QUERY_SNAPSHOT_METHODS(X) \ X(Query, "getQuery", "()Lcom/google/firebase/firestore/Query;"), \ X(Metadata, "getMetadata", \ "()Lcom/google/firebase/firestore/SnapshotMetadata;"), \ X(DocumentChanges, "getDocumentChanges", \ "(Lcom/google/firebase/firestore/MetadataChanges;)Ljava/util/List;"), \ X(Documents, "getDocuments", "()Ljava/util/List;"), \ X(Size, "size", "()I") // clang-format on METHOD_LOOKUP_DECLARATION(query_snapshot, QUERY_SNAPSHOT_METHODS) METHOD_LOOKUP_DEFINITION(query_snapshot, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/QuerySnapshot", QUERY_SNAPSHOT_METHODS) Query QuerySnapshotInternal::query() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject query = env->CallObjectMethod( obj_, query_snapshot::GetMethodId(query_snapshot::kQuery)); QueryInternal* internal = new QueryInternal{firestore_, query}; env->DeleteLocalRef(query); CheckAndClearJniExceptions(env); return Query{internal}; } SnapshotMetadata QuerySnapshotInternal::metadata() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject metadata = env->CallObjectMethod( obj_, query_snapshot::GetMethodId(query_snapshot::kMetadata)); SnapshotMetadata result = SnapshotMetadataInternal::JavaSnapshotMetadataToSnapshotMetadata( env, metadata); CheckAndClearJniExceptions(env); return result; } std::vector<DocumentChange> QuerySnapshotInternal::DocumentChanges( MetadataChanges metadata_changes) const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject j_metadata_changes = MetadataChangesInternal::ToJavaObject(env, metadata_changes); jobject change_list = env->CallObjectMethod( obj_, query_snapshot::GetMethodId(query_snapshot::kDocumentChanges), j_metadata_changes); CheckAndClearJniExceptions(env); std::vector<DocumentChange> result; JavaListToStdVector<DocumentChange, DocumentChangeInternal>( firestore_, change_list, &result); return result; } std::vector<DocumentSnapshot> QuerySnapshotInternal::documents() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject document_list = env->CallObjectMethod( obj_, query_snapshot::GetMethodId(query_snapshot::kDocuments)); CheckAndClearJniExceptions(env); std::vector<DocumentSnapshot> result; JavaListToStdVector<DocumentSnapshot, DocumentSnapshotInternal>( firestore_, document_list, &result); env->DeleteLocalRef(document_list); return result; } std::size_t QuerySnapshotInternal::size() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jint result = env->CallIntMethod( obj_, query_snapshot::GetMethodId(query_snapshot::kSize)); CheckAndClearJniExceptions(env); return static_cast<std::size_t>(result); } /* static */ bool QuerySnapshotInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = query_snapshot::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void QuerySnapshotInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); query_snapshot::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>#include "firestore/src/ios/document_snapshot_ios.h" #include <utility> #include "firestore/src/include/firebase/firestore.h" #include "firestore/src/ios/converter_ios.h" #include "firestore/src/ios/util_ios.h" #include "absl/memory/memory.h" #include "Firestore/core/src/firebase/firestore/api/document_reference.h" #include "Firestore/core/src/firebase/firestore/model/database_id.h" #include "Firestore/core/src/firebase/firestore/model/document_key.h" #include "Firestore/core/src/firebase/firestore/model/field_path.h" #include "Firestore/core/src/firebase/firestore/model/field_value_options.h" #include "Firestore/core/src/firebase/firestore/nanopb/byte_string.h" namespace firebase { namespace firestore { using ServerTimestampBehavior = DocumentSnapshot::ServerTimestampBehavior; using Type = model::FieldValue::Type; using model::DocumentKey; DocumentSnapshotInternal::DocumentSnapshotInternal( api::DocumentSnapshot&& snapshot) : snapshot_{std::move(snapshot)} {} Firestore* DocumentSnapshotInternal::firestore() { return GetFirestore(&snapshot_); } FirestoreInternal* DocumentSnapshotInternal::firestore_internal() { return GetFirestoreInternal(&snapshot_); } const FirestoreInternal* DocumentSnapshotInternal::firestore_internal() const { return GetFirestoreInternal(&snapshot_); } const std::string& DocumentSnapshotInternal::id() const { return snapshot_.document_id(); } DocumentReference DocumentSnapshotInternal::reference() const { return MakePublic(snapshot_.CreateReference()); } SnapshotMetadata DocumentSnapshotInternal::metadata() const { const auto& result = snapshot_.metadata(); return SnapshotMetadata{result.pending_writes(), result.from_cache()}; } bool DocumentSnapshotInternal::exists() const { return snapshot_.exists(); } MapFieldValue DocumentSnapshotInternal::GetData( ServerTimestampBehavior stb) const { using Map = model::FieldValue::Map; absl::optional<model::ObjectValue> maybe_object = snapshot_.GetData(); const Map& map = maybe_object ? maybe_object.value().GetInternalValue() : Map{}; FieldValue result = ConvertObject(map, stb); HARD_ASSERT_IOS(result.type() == FieldValue::Type::kMap, "Expected snapshot data to parse to a map"); return result.map_value(); } FieldValue DocumentSnapshotInternal::Get(const FieldPath& field, ServerTimestampBehavior stb) const { return GetValue(GetInternal(field), stb); } FieldValue DocumentSnapshotInternal::GetValue( const model::FieldPath& path, ServerTimestampBehavior stb) const { absl::optional<model::FieldValue> maybe_value = snapshot_.GetValue(path); if (maybe_value) { return ConvertAnyValue(std::move(maybe_value).value(), stb); } else { return FieldValue(); } } // FieldValue parsing FieldValue DocumentSnapshotInternal::ConvertAnyValue( const model::FieldValue& input, ServerTimestampBehavior stb) const { switch (input.type()) { case Type::Object: return ConvertObject(input.object_value(), stb); case Type::Array: return ConvertArray(input.array_value(), stb); default: return ConvertScalar(input, stb); } } FieldValue DocumentSnapshotInternal::ConvertObject( const model::FieldValue::Map& object, ServerTimestampBehavior stb) const { MapFieldValue result; for (const auto& kv : object) { result[kv.first] = ConvertAnyValue(kv.second, stb); } return FieldValue::FromMap(std::move(result)); } FieldValue DocumentSnapshotInternal::ConvertArray( const model::FieldValue::Array& array, ServerTimestampBehavior stb) const { std::vector<FieldValue> result; for (const auto& value : array) { result.push_back(ConvertAnyValue(value, stb)); } return FieldValue::FromArray(std::move(result)); } FieldValue DocumentSnapshotInternal::ConvertScalar( const model::FieldValue& scalar, ServerTimestampBehavior stb) const { switch (scalar.type()) { case Type::Null: return FieldValue::Null(); case Type::Boolean: return FieldValue::FromBoolean(scalar.boolean_value()); case Type::Integer: return FieldValue::FromInteger(scalar.integer_value()); case Type::Double: return FieldValue::FromDouble(scalar.double_value()); case Type::String: return FieldValue::FromString(scalar.string_value()); case Type::Timestamp: return FieldValue::FromTimestamp(scalar.timestamp_value()); case Type::GeoPoint: return FieldValue::FromGeoPoint(scalar.geo_point_value()); case Type::Blob: return FieldValue::FromBlob(scalar.blob_value().data(), scalar.blob_value().size()); case Type::Reference: return ConvertReference(scalar.reference_value()); case Type::ServerTimestamp: return ConvertServerTimestamp(scalar.server_timestamp_value(), stb); default: { // TODO(b/147444199): use string formatting. // HARD_FAIL("Unexpected kind of FieldValue: '%s'", scalar.type()); auto message = std::string("Unexpected kind of FieldValue: '") + std::to_string(static_cast<int>(scalar.type())) + "'"; HARD_FAIL_IOS(message.c_str()); } } } FieldValue DocumentSnapshotInternal::ConvertReference( const model::FieldValue::Reference& reference) const { HARD_ASSERT_IOS( reference.database_id() == firestore_internal()->database_id(), "Converted reference is from another database"); api::DocumentReference api_reference{reference.key(), snapshot_.firestore()}; return FieldValue::FromReference(MakePublic(std::move(api_reference))); } FieldValue DocumentSnapshotInternal::ConvertServerTimestamp( const model::FieldValue::ServerTimestamp& server_timestamp, ServerTimestampBehavior stb) const { switch (stb) { case ServerTimestampBehavior::kNone: return FieldValue::Null(); case ServerTimestampBehavior::kEstimate: { return FieldValue::FromTimestamp(server_timestamp.local_write_time()); } case ServerTimestampBehavior::kPrevious: if (server_timestamp.previous_value()) { return ConvertScalar(server_timestamp.previous_value().value(), stb); } return FieldValue::Null(); } UNREACHABLE(); } } // namespace firestore } // namespace firebase <file_sep>#include "firestore/src/include/firebase/firestore/transaction.h" #include "app/src/assert.h" #include "firestore/src/common/cleanup.h" #include "firestore/src/include/firebase/firestore/document_reference.h" #include "firestore/src/include/firebase/firestore/document_snapshot.h" #if defined(__ANDROID__) #include "firestore/src/android/transaction_android.h" #elif defined(FIRESTORE_STUB_BUILD) #include "firestore/src/stub/transaction_stub.h" #else #include "firestore/src/ios/transaction_ios.h" #endif // defined(__ANDROID__) namespace firebase { namespace firestore { using CleanupFnTransaction = CleanupFn<Transaction, TransactionInternal>; Transaction::Transaction(TransactionInternal* internal) : internal_(internal) { FIREBASE_ASSERT(internal != nullptr); CleanupFnTransaction::Register(this, internal_); } Transaction::~Transaction() { CleanupFnTransaction::Unregister(this, internal_); delete internal_; internal_ = nullptr; } void Transaction::Set(const DocumentReference& document, const MapFieldValue& data, const SetOptions& options) { if (!internal_) return; internal_->Set(document, data, options); } void Transaction::Update(const DocumentReference& document, const MapFieldValue& data) { if (!internal_) return; internal_->Update(document, data); } void Transaction::Update(const DocumentReference& document, const MapFieldPathValue& data) { if (!internal_) return; internal_->Update(document, data); } void Transaction::Delete(const DocumentReference& document) { if (!internal_) return; internal_->Delete(document); } DocumentSnapshot Transaction::Get(const DocumentReference& document, Error* error_code, std::string* error_message) { if (!internal_) return {}; return internal_->Get(document, error_code, error_message); } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_COMMON_TO_STRING_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_COMMON_TO_STRING_H_ #include <iosfwd> #include <string> #include "firestore/src/include/firebase/firestore/map_field_value.h" // This file contains string converters that aren't exposed publicly but are // used by more than one of the public string converters in their // implementation. namespace firebase { namespace firestore { // Returns a string representation of the given `MapFieldValue` for // logging/debugging purposes. // // Note: the exact string representation is unspecified and subject to change; // don't rely on the format of the string. std::string ToString(const MapFieldValue& value); // Outputs the string representation of the given `MapFieldValue` to the given // stream. // // See `ToString` above for comments on the representation format. // std::ostream& operator<<(std::ostream& out, const MapFieldValue& value); } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_COMMON_TO_STRING_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_FIREBASE_FIRESTORE_SETTINGS_IOS_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_FIREBASE_FIRESTORE_SETTINGS_IOS_H_ #include "firestore/src/include/firebase/firestore/settings.h" #include "Firestore/core/src/firebase/firestore/api/settings.h" namespace firebase { namespace firestore { api::Settings ToCoreApi(const Settings& settings); } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_FIREBASE_FIRESTORE_SETTINGS_IOS_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_METADATA_CHANGES_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_METADATA_CHANGES_ANDROID_H_ #include <jni.h> #include "app/src/include/firebase/app.h" #include "app/src/util_android.h" #include "firestore/src/include/firebase/firestore/metadata_changes.h" namespace firebase { namespace firestore { class MetadataChangesInternal { public: using ApiType = MetadataChanges; static jobject ToJavaObject(JNIEnv* env, MetadataChanges metadata_changes); private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); static jobject exclude_; static jobject include_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_METADATA_CHANGES_ANDROID_H_ <file_sep>#include "firestore/src/ios/hard_assert_ios.h" namespace firebase { namespace firestore { namespace util { ABSL_ATTRIBUTE_NORETURN void ThrowInvalidArgumentIos( const std::string& message) { Throw(ExceptionType::InvalidArgument, nullptr, nullptr, 0, message); } } // namespace util } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_FIREBASE_FIRESTORE_SETTINGS_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_FIREBASE_FIRESTORE_SETTINGS_ANDROID_H_ #include <jni.h> #include "app/src/include/firebase/app.h" #include "app/src/util_android.h" #include "firestore/src/include/firebase/firestore/settings.h" namespace firebase { namespace firestore { class FirebaseFirestoreSettingsInternal { public: using ApiType = Settings; static jobject SettingToJavaSetting(JNIEnv* env, const Settings& settings); static Settings JavaSettingToSetting(JNIEnv* env, jobject obj); private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_FIREBASE_FIRESTORE_SETTINGS_ANDROID_H_ <file_sep>#include "firestore/src/android/snapshot_metadata_android.h" #include <stdint.h> #include "app/src/util_android.h" #include "firestore/src/android/util_android.h" namespace firebase { namespace firestore { // clang-format off #define SNAPSHOT_METADATA_METHODS(X) \ X(Constructor, "<init>", "(ZZ)V", util::kMethodTypeInstance), \ X(HasPendingWrites, "hasPendingWrites", "()Z"), \ X(IsFromCache, "isFromCache", "()Z") // clang-format on METHOD_LOOKUP_DECLARATION(snapshot_metadata, SNAPSHOT_METADATA_METHODS) METHOD_LOOKUP_DEFINITION(snapshot_metadata, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/SnapshotMetadata", SNAPSHOT_METADATA_METHODS) /* static */ jobject SnapshotMetadataInternal::SnapshotMetadataToJavaSnapshotMetadata( JNIEnv* env, const SnapshotMetadata& metadata) { jobject result = env->NewObject( snapshot_metadata::GetClass(), snapshot_metadata::GetMethodId(snapshot_metadata::kConstructor), static_cast<jboolean>(metadata.has_pending_writes()), static_cast<jboolean>(metadata.is_from_cache())); CheckAndClearJniExceptions(env); return result; } /* static */ SnapshotMetadata SnapshotMetadataInternal::JavaSnapshotMetadataToSnapshotMetadata(JNIEnv* env, jobject obj) { jboolean has_pending_writes = env->CallBooleanMethod( obj, snapshot_metadata::GetMethodId(snapshot_metadata::kHasPendingWrites)); jboolean is_from_cache = env->CallBooleanMethod( obj, snapshot_metadata::GetMethodId(snapshot_metadata::kIsFromCache)); env->DeleteLocalRef(obj); CheckAndClearJniExceptions(env); return SnapshotMetadata{static_cast<bool>(has_pending_writes), static_cast<bool>(is_from_cache)}; } /* static */ bool SnapshotMetadataInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = snapshot_metadata::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void SnapshotMetadataInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); snapshot_metadata::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>#include "firebase/csharp/document_event_listener.h" #include "app/src/assert.h" #include "firebase/firestore/document_reference.h" namespace firebase { namespace firestore { namespace csharp { ::firebase::Mutex DocumentEventListener::g_mutex; DocumentEventListenerCallback DocumentEventListener::g_document_snapshot_event_listener_callback = nullptr; void DocumentEventListener::OnEvent(const DocumentSnapshot& value, Error error) { MutexLock lock(g_mutex); if (g_document_snapshot_event_listener_callback) { firebase::callback::AddCallback(firebase::callback::NewCallback( DocumentSnapshotEvent, callback_id_, value, error)); } } /* static */ void DocumentEventListener::SetCallback( DocumentEventListenerCallback callback) { MutexLock lock(g_mutex); if (!callback) { g_document_snapshot_event_listener_callback = nullptr; return; } if (g_document_snapshot_event_listener_callback) { FIREBASE_ASSERT(g_document_snapshot_event_listener_callback == callback); } else { g_document_snapshot_event_listener_callback = callback; } } /* static */ ListenerRegistration DocumentEventListener::AddListenerTo( int32_t callback_id, DocumentReference reference, MetadataChanges metadata_changes) { DocumentEventListener listener(callback_id); // TODO(zxu): For now, we call the one with lambda instead of EventListener // pointer so we do not have to manage the ownership of the listener. We // might want to extend the design to manage listeners and call the one with // EventListener parameter e.g. adding extra parameter in the API to specify // whether ownership is transferred. return reference.AddSnapshotListener( metadata_changes, [listener](const DocumentSnapshot& value, Error error) mutable { listener.OnEvent(value, error); }); } /* static */ void DocumentEventListener::DocumentSnapshotEvent(int callback_id, DocumentSnapshot value, Error error) { MutexLock lock(g_mutex); if (error != Ok || g_document_snapshot_event_listener_callback == nullptr) { return; } // The ownership is passed through the call to C# handler. DocumentSnapshot* copy = new DocumentSnapshot(value); g_document_snapshot_event_listener_callback(callback_id, copy); } } // namespace csharp } // namespace firestore } // namespace firebase <file_sep>// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "database/src/desktop/query_desktop.h" #include <sstream> #include "app/memory/unique_ptr.h" #include "app/rest/transport_builder.h" #include "app/rest/transport_curl.h" #include "app/rest/util.h" #include "app/src/callback.h" #include "app/src/function_registry.h" #include "app/src/semaphore.h" #include "app/src/thread.h" #include "app/src/variant_util.h" #include "database/src/common/query.h" #include "database/src/desktop/connection/host_info.h" #include "database/src/desktop/core/child_event_registration.h" #include "database/src/desktop/core/event_registration.h" #include "database/src/desktop/core/value_event_registration.h" #include "database/src/desktop/data_snapshot_desktop.h" #include "database/src/desktop/database_desktop.h" #include "database/src/desktop/database_reference_desktop.h" #include "database/src/desktop/util_desktop.h" namespace firebase { using callback::NewCallback; namespace database { namespace internal { // This method validates that key index has been called with the correct // combination of parameters static bool ValidateQueryEndpoints(const QueryParams& params, Logger* logger) { if (params.order_by == QueryParams::kOrderByKey) { const char message[] = "You must use StartAt(String value), EndAt(String value) or " "EqualTo(String value) in combination with orderByKey(). Other type of " "values or using the version with 2 parameters is not supported"; if (HasStart(params)) { const Variant& start_node = GetStartValue(params); std::string start_name = GetStartName(params); if ((start_name != QueryParamsComparator::kMinKey) || !(start_node.is_string())) { logger->LogWarning(message); return false; } } if (HasEnd(params)) { const Variant& end_node = GetEndValue(params); std::string end_name = GetEndName(params); if ((end_name != QueryParamsComparator::kMaxKey) || !(end_node.is_string())) { logger->LogWarning(message); return false; } } } else { if (params.order_by == QueryParams::kOrderByPriority) { if ((HasStart(params) && !IsValidPriority(GetStartValue(params))) || (HasEnd(params) && !IsValidPriority(GetEndValue(params)))) { logger->LogWarning( "When using orderByPriority(), values provided to " "StartAt(), EndAt(), or EqualTo() must be valid " "priorities."); return false; } } } return true; } QueryInternal::QueryInternal(DatabaseInternal* database, const QuerySpec& query_spec) : database_(database), query_spec_(query_spec) { database_->future_manager().AllocFutureApi(&future_api_id_, kQueryFnCount); } QueryInternal::QueryInternal(const QueryInternal& internal) : database_(internal.database_), query_spec_(internal.query_spec_) { database_->future_manager().AllocFutureApi(&future_api_id_, kQueryFnCount); } QueryInternal& QueryInternal::operator=(const QueryInternal& internal) { database_ = internal.database_; query_spec_ = internal.query_spec_; return *this; } #if defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) QueryInternal::QueryInternal(QueryInternal&& internal) : database_(internal.database_), query_spec_(std::move(internal.query_spec_)) { database_->future_manager().MoveFutureApi(&internal.future_api_id_, &future_api_id_); } QueryInternal& QueryInternal::operator=(QueryInternal&& internal) { database_ = internal.database_; query_spec_ = std::move(internal.query_spec_); database_->future_manager().MoveFutureApi(&internal.future_api_id_, &future_api_id_); return *this; } #endif // defined(FIREBASE_USE_MOVE_OPERATORS) || defined(DOXYGEN) QueryInternal::~QueryInternal() {} class SingleValueEventRegistration : public ValueEventRegistration { public: SingleValueEventRegistration(DatabaseInternal* database, SingleValueListener** single_listener_holder, const QuerySpec& query_spec) : ValueEventRegistration(database, *single_listener_holder, query_spec), listener_mutex_(database->listener_mutex()), single_listener_holder_(single_listener_holder) {} void FireEvent(const Event& event) override { MutexLock lock(*listener_mutex_); if (single_listener_holder_ && *single_listener_holder_) { single_listener_holder_ = nullptr; ValueEventRegistration::FireEvent(event); } } void FireCancelEvent(Error error) { MutexLock lock(*listener_mutex_); if (single_listener_holder_ && *single_listener_holder_) { single_listener_holder_ = nullptr; ValueEventRegistration::FireCancelEvent(error); } } private: Mutex* listener_mutex_; SingleValueListener** single_listener_holder_; }; Future<DataSnapshot> QueryInternal::GetValue() { SafeFutureHandle<DataSnapshot> handle = query_future()->SafeAlloc<DataSnapshot>(kQueryFnGetValue, DataSnapshot(nullptr)); // TODO(b/68878322): Refactor this code to be less brittle, possibly using the // CleanupNotifier or something like it. SingleValueListener* single_listener = new SingleValueListener(database_, query_spec_, query_future(), handle); // If the database goes away, we need to be able to reach into these blocks // and clear their single_listener pointer. We can't do that directly, but we // can cache a pointer to the pointer, and clear that instead. SingleValueListener** single_listener_holder = database_->AddSingleValueListener(single_listener); AddEventRegistration(MakeUnique<SingleValueEventRegistration>( database_, single_listener_holder, query_spec_)); return MakeFuture(query_future(), handle); } Future<DataSnapshot> QueryInternal::GetValueLastResult() { return static_cast<const Future<DataSnapshot>&>( query_future()->LastResult(kQueryFnGetValue)); } void QueryInternal::AddValueListener(ValueListener* listener) { ValueListenerCleanupData cleanup_data(query_spec_); AddEventRegistration( MakeUnique<ValueEventRegistration>(database_, listener, query_spec_)); database_->RegisterValueListener(query_spec_, listener, std::move(cleanup_data)); } void QueryInternal::RemoveValueListener(ValueListener* listener) { RemoveEventRegistration(listener, query_spec_); database_->UnregisterValueListener(query_spec_, listener); } void QueryInternal::RemoveAllValueListeners() { RemoveEventRegistration(static_cast<void*>(nullptr), query_spec_); database_->UnregisterAllValueListeners(query_spec_); } void QueryInternal::AddEventRegistration( UniquePtr<EventRegistration> registration) { Repo::scheduler().Schedule(NewCallback( [](Repo::ThisRef ref, UniquePtr<EventRegistration> registration) { Repo::ThisRefLock lock(&ref); if (lock.GetReference() != nullptr) { lock.GetReference()->AddEventCallback(Move(registration)); } }, database_->repo()->this_ref(), Move(registration))); } void QueryInternal::RemoveEventRegistration(void* listener_ptr, const QuerySpec& query_spec) { Repo::scheduler().Schedule(NewCallback( [](Repo::ThisRef ref, void* listener_ptr, QuerySpec query_spec) { Repo::ThisRefLock lock(&ref); if (lock.GetReference() != nullptr) { lock.GetReference()->RemoveEventCallback(listener_ptr, query_spec); } }, database_->repo()->this_ref(), listener_ptr, query_spec)); } void QueryInternal::RemoveEventRegistration(ValueListener* listener, const QuerySpec& query_spec) { RemoveEventRegistration(static_cast<void*>(listener), query_spec); } void QueryInternal::RemoveEventRegistration(ChildListener* listener, const QuerySpec& query_spec) { RemoveEventRegistration(static_cast<void*>(listener), query_spec); } void QueryInternal::AddChildListener(ChildListener* listener) { ChildListenerCleanupData cleanup_data(query_spec_); AddEventRegistration( MakeUnique<ChildEventRegistration>(database_, listener, query_spec_)); database_->RegisterChildListener(query_spec_, listener, std::move(cleanup_data)); } void QueryInternal::RemoveChildListener(ChildListener* listener) { RemoveEventRegistration(listener, query_spec_); database_->UnregisterChildListener(query_spec_, listener); } void QueryInternal::RemoveAllChildListeners() { RemoveEventRegistration(static_cast<void*>(nullptr), query_spec_); database_->UnregisterAllChildListeners(query_spec_); } DatabaseReferenceInternal* QueryInternal::GetReference() { return new DatabaseReferenceInternal(database_, query_spec_.path); } void QueryInternal::SetKeepSynchronized(bool keep_synchronized) { Repo::scheduler().Schedule(NewCallback( [](Repo::ThisRef ref, QuerySpec query_spec, bool keep_synchronized) { Repo::ThisRefLock lock(&ref); if (lock.GetReference() != nullptr) { lock.GetReference()->SetKeepSynchronized(query_spec, keep_synchronized); } }, database_->repo()->this_ref(), query_spec_, keep_synchronized)); } QueryInternal* QueryInternal::OrderByChild(const char* path) { QuerySpec spec = query_spec_; spec.params.order_by = QueryParams::kOrderByChild; spec.params.order_by_child = path; return new QueryInternal(database_, spec); } QueryInternal* QueryInternal::OrderByKey() { QuerySpec spec = query_spec_; spec.params.order_by = QueryParams::kOrderByKey; return new QueryInternal(database_, spec); } QueryInternal* QueryInternal::OrderByPriority() { QuerySpec spec = query_spec_; spec.params.order_by = QueryParams::kOrderByPriority; return new QueryInternal(database_, spec); } QueryInternal* QueryInternal::OrderByValue() { QuerySpec spec = query_spec_; spec.params.order_by = QueryParams::kOrderByValue; return new QueryInternal(database_, spec); } QueryInternal* QueryInternal::StartAt(const Variant& value) { Logger* logger = database_->logger(); if (!value.is_numeric() && !value.is_string() && !value.is_bool()) { logger->LogWarning( "Query::StartAt(): Only strings, numbers, and boolean values are " "allowed. (URL = %s)", query_spec_.path.c_str()); return nullptr; } if (HasStart(query_spec_.params)) { logger->LogWarning("Can't Call StartAt() or EqualTo() multiple times"); return nullptr; } QuerySpec spec = query_spec_; spec.params.start_at_value = value; if (!ValidateQueryEndpoints(spec.params, database_->logger())) { return nullptr; } return new QueryInternal(database_, spec); } QueryInternal* QueryInternal::StartAt(const Variant& value, const char* child_key) { Logger* logger = database_->logger(); if (!value.is_numeric() && !value.is_string() && !value.is_bool()) { logger->LogWarning( "Query::StartAt: Only strings, numbers, and boolean values are " "allowed. (URL = %s)", query_spec_.path.c_str()); return nullptr; } FIREBASE_ASSERT_RETURN(nullptr, child_key != nullptr); QuerySpec spec = query_spec_; spec.params.start_at_value = value; spec.params.start_at_child_key = child_key; if (!ValidateQueryEndpoints(spec.params, database_->logger())) { return nullptr; } return new QueryInternal(database_, spec); } QueryInternal* QueryInternal::EndAt(const Variant& value) { Logger* logger = database_->logger(); if (!value.is_numeric() && !value.is_string() && !value.is_bool()) { logger->LogWarning( "Query::EndAt: Only strings, numbers, and boolean values are " "allowed. (URL = %s)", query_spec_.path.c_str()); return nullptr; } if (HasEnd(query_spec_.params)) { logger->LogWarning("Can't Call EndAt() or EqualTo() multiple times"); return nullptr; } QuerySpec spec = query_spec_; spec.params.end_at_value = value; if (!ValidateQueryEndpoints(spec.params, database_->logger())) { return nullptr; } return new QueryInternal(database_, spec); } QueryInternal* QueryInternal::EndAt(const Variant& value, const char* child_key) { Logger* logger = database_->logger(); if (!value.is_numeric() && !value.is_string() && !value.is_bool()) { logger->LogWarning( "Query::EndAt: Only strings, numbers, and boolean values are " "allowed. (URL = %s)", query_spec_.path.c_str()); return nullptr; } FIREBASE_ASSERT_RETURN(nullptr, child_key != nullptr); QuerySpec spec = query_spec_; spec.params.end_at_value = value; spec.params.end_at_child_key = child_key; if (!ValidateQueryEndpoints(spec.params, database_->logger())) { return nullptr; } return new QueryInternal(database_, spec); } QueryInternal* QueryInternal::EqualTo(const Variant& value) { Logger* logger = database_->logger(); if (!value.is_numeric() && !value.is_string() && !value.is_bool()) { logger->LogWarning( "Query::EqualTo: Only strings, numbers, and boolean values are " "allowed. (URL = %s)", query_spec_.path.c_str()); return nullptr; } QuerySpec spec = query_spec_; spec.params.equal_to_value = value; if (!ValidateQueryEndpoints(spec.params, database_->logger())) { return nullptr; } return new QueryInternal(database_, spec); } QueryInternal* QueryInternal::EqualTo(const Variant& value, const char* child_key) { Logger* logger = database_->logger(); if (!value.is_numeric() && !value.is_string() && !value.is_bool()) { logger->LogWarning( "Query::EqualTo: Only strings, numbers, and boolean values are " "allowed. (URL = %s)", query_spec_.path.c_str()); return nullptr; } QuerySpec spec = query_spec_; spec.params.equal_to_value = value; spec.params.equal_to_child_key = child_key; if (!ValidateQueryEndpoints(spec.params, database_->logger())) { return nullptr; } return new QueryInternal(database_, spec); } QueryInternal* QueryInternal::LimitToFirst(size_t limit) { QuerySpec spec = query_spec_; spec.params.limit_first = limit; return new QueryInternal(database_, spec); } QueryInternal* QueryInternal::LimitToLast(size_t limit) { QuerySpec spec = query_spec_; spec.params.limit_last = limit; return new QueryInternal(database_, spec); } ReferenceCountedFutureImpl* QueryInternal::query_future() { return database_->future_manager().GetFutureApi(&future_api_id_); } } // namespace internal } // namespace database } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_DOCUMENT_CHANGE_TYPE_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_DOCUMENT_CHANGE_TYPE_ANDROID_H_ #include <jni.h> #include <map> #include "app/src/include/firebase/app.h" #include "firestore/src/include/firebase/firestore/document_change.h" namespace firebase { namespace firestore { class DocumentChangeTypeInternal { public: static DocumentChange::Type JavaDocumentChangeTypeToDocumentChangeType( JNIEnv* env, jobject type); private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); static std::map<DocumentChange::Type, jobject>* cpp_enum_to_java_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_DOCUMENT_CHANGE_TYPE_ANDROID_H_ <file_sep>// Copyright 2017 Google Inc. All Rights Reserved. #ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_COMMON_CLEANUP_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_COMMON_CLEANUP_H_ #include "firestore/src/include/firebase/firestore/listener_registration.h" namespace firebase { namespace firestore { class FirestoreInternal; // T is a Firestore public type. U is a internal type that can provide a // FirestoreInternal instance. Normally U is just the internal type of T. // // F is almost always FirestoreInternal unless one wants something else to // manage the cleanup process. We define type F to make this CleanupFn // implementation platform-independent. template <typename T, typename U, typename F = FirestoreInternal> struct CleanupFn { static void Cleanup(void* obj_void) { DoCleanup(static_cast<T*>(obj_void)); } static void Register(T* obj, F* firestore) { if (firestore) { firestore->cleanup().RegisterObject(obj, CleanupFn<T, U>::Cleanup); } } static void Register(T* obj, U* internal) { if (internal) { Register(obj, internal->firestore_internal()); } } static void Unregister(T* obj, F* firestore) { if (firestore) { firestore->cleanup().UnregisterObject(obj); } } static void Unregister(T* obj, U* internal) { if (internal) { Unregister(obj, internal->firestore_internal()); } } private: template <typename Object> static void DoCleanup(Object* obj) { delete obj->internal_; obj->internal_ = nullptr; } // `ListenerRegistration` objects differ from the common pattern. static void DoCleanup(ListenerRegistration* obj) { obj->Cleanup(); } }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_COMMON_CLEANUP_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_DOCUMENT_EVENT_LISTENER_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_DOCUMENT_EVENT_LISTENER_H_ #include <cstdint> #include "app/src/callback.h" #include "app/src/mutex.h" #include "firebase/firestore/document_snapshot.h" #include "firebase/firestore/event_listener.h" #include "firebase/firestore/listener_registration.h" #include "firebase/firestore/metadata_changes.h" namespace firebase { namespace firestore { namespace csharp { // Add this to make this header compile when SWIG is not involved. #ifndef SWIGSTDCALL #if !defined(SWIG) && \ (defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)) #define SWIGSTDCALL __stdcall #else #define SWIGSTDCALL #endif #endif // The callbacks that are used by the listener, that need to reach back to C# // callbacks. typedef void(SWIGSTDCALL* DocumentEventListenerCallback)(int callback_id, void* snapshot); // Provide a C++ implementation of the EventListener for DocumentSnapshot that // can forward the calls back to the C# delegates. class DocumentEventListener : public EventListener<DocumentSnapshot> { public: explicit DocumentEventListener(int32_t callback_id) : callback_id_(callback_id) {} void OnEvent(const DocumentSnapshot& value, Error error) override; static void SetCallback(DocumentEventListenerCallback callback); static ListenerRegistration AddListenerTo(int32_t callback_id, DocumentReference reference, MetadataChanges metadataChanges); private: static void DocumentSnapshotEvent(int callback_id, DocumentSnapshot value, Error error); int32_t callback_id_; // These static variables are named as global variable instead of private // class member. static Mutex g_mutex; static DocumentEventListenerCallback g_document_snapshot_event_listener_callback; }; } // namespace csharp } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_DOCUMENT_EVENT_LISTENER_H_ <file_sep>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef FIREBASE_APP_CLIENT_CPP_INSTANCE_ID_INSTANCE_ID_DESKTOP_IMPL_H_ #define FIREBASE_APP_CLIENT_CPP_INSTANCE_ID_INSTANCE_ID_DESKTOP_IMPL_H_ #include <cstdint> #include <map> #include <string> #include "app/memory/unique_ptr.h" #include "app/src/callback.h" #include "app/src/future_manager.h" #include "app/src/include/firebase/app.h" #include "app/src/include/firebase/future.h" #include "app/src/mutex.h" #include "app/src/scheduler.h" #include "app/src/secure/user_secure_manager.h" #include "app/src/semaphore.h" namespace firebase { namespace rest { class Request; class Transport; } // namespace rest namespace instance_id { namespace internal { class InstanceIdDesktopImplTest; // For testing. class NetworkOperation; // Defined in instance_id_desktop_impl.cc class SignalSemaphoreResponse; // Defined in instance_id_desktop_impl.cc class InstanceIdDesktopImpl { public: // Future functions for Instance Id enum InstanceIdFn { kInstanceIdFnGetId = 0, kInstanceIdFnRemoveId, kInstanceIdFnGetToken, kInstanceIdFnRemoveToken, kInstanceIdFnStorageSave, kInstanceIdFnStorageLoad, kInstanceIdFnStorageDelete, kInstanceIdFnCount, }; // Errors for Instance Id futures enum Error { // The operation was a success, no error occurred. kErrorNone = 0, // The service is unavailable. kErrorUnavailable, // An unknown error occurred. kErrorUnknownError, // App shutdown is in progress. kErrorShutdown, }; virtual ~InstanceIdDesktopImpl(); // InstanceIdDesktopImpl is neither copyable nor movable. InstanceIdDesktopImpl(const InstanceIdDesktopImpl&) = delete; InstanceIdDesktopImpl& operator=(const InstanceIdDesktopImpl&) = delete; InstanceIdDesktopImpl(InstanceIdDesktopImpl&&) = delete; InstanceIdDesktopImpl& operator=(InstanceIdDesktopImpl&&) = delete; // Returns the InstanceIdRestImpl object for an App and creating the // InstanceIdRestImpl if required. static InstanceIdDesktopImpl* GetInstance(App* app); // Returns a stable identifier that uniquely identifies the app Future<std::string> GetId(); // Get the results of the most recent call to @ref GetId. Future<std::string> GetIdLastResult(); // Delete the ID associated with the app, revoke all tokens and // allocate a new ID. Future<void> DeleteId(); // Get the results of the most recent call to @ref DeleteId. Future<void> DeleteIdLastResult(); // Returns a token that authorizes an Entity to perform an action on // behalf of the application identified by Instance ID. Future<std::string> GetToken(const char* scope); // Get the results of the most recent call to @ref GetToken. Future<std::string> GetTokenLastResult(); // Revokes access to a scope (action) Future<void> DeleteToken(const char* scope); // Get the results of the most recent call to @ref DeleteToken. Future<void> DeleteTokenLastResult(); // Gets the App this object is connected to. App& app() { return *app_; } private: friend class InstanceIdDesktopImplTest; // Data cached from a check-in and required to perform instance ID operations. struct CheckinData { CheckinData() : last_checkin_time_ms(0) {} // Reset to the default state. void Clear() { security_token.clear(); device_id.clear(); digest.clear(); last_checkin_time_ms = 0; } // Security token from the last check-in. std::string security_token; // Device ID from the last check-in. std::string device_id; // Digest from the previous checkin. std::string digest; // Last check-in time in milliseconds since the Linux epoch. uint64_t last_checkin_time_ms; }; // Fetches a token with expodential backoff using the scheduler. class FetchServerTokenCallback : public callback::Callback { public: FetchServerTokenCallback(InstanceIdDesktopImpl* iid, const std::string& scope, SafeFutureHandle<std::string> future_handle) : iid_(iid), scope_(scope), future_handle_(future_handle), retry_delay_time_(0) {} void Run() override; private: InstanceIdDesktopImpl* iid_; std::string scope_; SafeFutureHandle<std::string> future_handle_; uint64_t retry_delay_time_; }; explicit InstanceIdDesktopImpl(App* app); // Get future manager of this object FutureManager& future_manager() { return future_manager_; } // Get the ReferenceCountedFutureImpl for this object ReferenceCountedFutureImpl* ref_future() { return future_manager().GetFutureApi(this); } // Verify and parse the stored IID data, called by LoadFromStorage(), and fill // in this class. Returns false if there are any parsing errors. bool ReadStoredInstanceIdData(const std::string& loaded_string); // For testing only, to use a fake UserSecureManager. void SetUserSecureManager( UniquePtr<firebase::app::secure::UserSecureManager> manager) { user_secure_manager_ = manager; } // Save the instance ID to local secure storage. Blocking. bool SaveToStorage(); // Load the instance ID from local secure storage. Blocking. bool LoadFromStorage(); // Delete the instance ID from local secure storage. Blocking. bool DeleteFromStorage(); // Fetch the current device ID and security token or check-in to retrieve // a new device ID and security token. bool InitialOrRefreshCheckin(); // Generate a new appid. This is 4 bits of 0x7 followed by 60 bits of // randomness, then base64-encoded until golden brown. std::string GenerateAppId(); // Find cached token for a scope. std::string FindCachedToken(const char* scope); // Clear a token for a scope. void DeleteCachedToken(const char* scope); // Perform a token fetch or delete network operation with an optional // callback to modify the request before the network operation is scheduled. void ServerTokenOperation(const char* scope, void (*request_callback)(rest::Request* request, void* state), void* state); // Fetch a token from the cache or retrieve a new token from the server. // The scope can be either "FCM" or "*" for remote config and other users. // retry is set to "true" if the server response requires a retry with // exponential back-off. bool FetchServerToken(const char* scope, bool* retry); // Delete a server-side token for a scope and remove it from the cache. // If delete_id is true all tokens are deleted along with the server // registration of instance ID. bool DeleteServerToken(const char* scope, bool delete_id); // Used to wait for async storage functions to finish. Semaphore storage_semaphore_; // Future manager of this object FutureManager future_manager_; // The App this object is connected to. App* app_; UniquePtr<firebase::app::secure::UserSecureManager> user_secure_manager_; CheckinData checkin_data_; // Cached instance ID. std::string instance_id_; // Tokens indexed by scope. std::map<std::string, std::string> tokens_; // Locale used to check-in. std::string locale_; // Time-zone used to check-in. std::string timezone_; // Logging ID for check-in requests. int logging_id_; // iOS device to spoof. std::string ios_device_model_; // iOS device version. std::string ios_device_version_; // Application version. std::string app_version_; // Operating system version. std::string os_version_; // Platform requesting a token. 0 = UNKNOWN int platform_; // Performs network operations for this object. UniquePtr<rest::Transport> transport_; Mutex network_operation_mutex_; // A network operation if a request is in progress, null otherwise. // Guarded by network_operation_mutex_. UniquePtr<NetworkOperation> network_operation_; // Buffer for the request in progress. std::string request_buffer_; // Signaled when the current network operation is complete. Semaphore network_operation_complete_; // Serializes all network operations from this object. scheduler::Scheduler scheduler_; // Whether tasks should continue to be scheduled. // Guarded by network_operation_mutex_. bool terminating_; // Global map of App to InstanceIdDesktopImpl static std::map<App*, InstanceIdDesktopImpl*> instance_id_by_app_; // Mutex to protect instance_id_by_app_ static Mutex instance_id_by_app_mutex_; }; } // namespace internal } // namespace instance_id } // namespace firebase #endif // FIREBASE_APP_CLIENT_CPP_INSTANCE_ID_INSTANCE_ID_DESKTOP_IMPL_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_FIREBASE_FIRESTORE_EXCEPTION_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_FIREBASE_FIRESTORE_EXCEPTION_ANDROID_H_ #include <string> #include "app/src/include/firebase/app.h" #include "app/src/util_android.h" #include "firebase/firestore/firestore_errors.h" namespace firebase { namespace firestore { class FirebaseFirestoreExceptionInternal { public: static Error ToErrorCode(JNIEnv* env, jobject exception); static std::string ToString(JNIEnv* env, jobject exception); static jthrowable ToException(JNIEnv* env, Error code, const char* message); static jthrowable ToException(JNIEnv* env, jthrowable exception); static bool IsInstance(JNIEnv* env, jobject exception); static bool IsFirestoreException(JNIEnv* env, jobject exception); private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_FIREBASE_FIRESTORE_EXCEPTION_ANDROID_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_TRANSACTION_STUB_H__ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_TRANSACTION_STUB_H__ #include "firestore/src/include/firebase/firestore/document_reference.h" #include "firestore/src/include/firebase/firestore/map_field_value.h" #include "firestore/src/include/firebase/firestore/transaction.h" #include "firestore/src/stub/firestore_stub.h" namespace firebase { namespace firestore { // This is the stub implementation of WriteBatch. class TransactionInternal { public: using ApiType = Transaction; TransactionInternal() {} FirestoreInternal* firestore_internal() const { return nullptr; } void Set(const DocumentReference& document, const MapFieldValue& data, const SetOptions& options) {} void Update(const DocumentReference& document, const MapFieldValue& data) {} void Update(const DocumentReference& document, const MapFieldPathValue& data) {} void Delete(const DocumentReference& document) {} DocumentSnapshot Get(const DocumentReference& document, Error* error_code, std::string* error_message) { return DocumentSnapshot{}; } }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_TRANSACTION_STUB_H__ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_DOCUMENT_SNAPSHOT_STUB_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_DOCUMENT_SNAPSHOT_STUB_H_ #include <map> #include <string> #include "app/src/include/firebase/app.h" #include "firestore/src/include/firebase/firestore/document_reference.h" #include "firestore/src/include/firebase/firestore/document_snapshot.h" #include "firestore/src/include/firebase/firestore/field_value.h" #include "firestore/src/include/firebase/firestore/snapshot_metadata.h" #include "firestore/src/stub/firestore_stub.h" namespace firebase { namespace firestore { // This is the stub implementation of DocumentSnapshot. class DocumentSnapshotInternal { public: using ApiType = DocumentSnapshot; FirestoreInternal* firestore_internal() const { return nullptr; } Firestore* firestore() const { return nullptr; } const std::string& id() const { return id_; } DocumentReference reference() const { return DocumentReference{}; } SnapshotMetadata metadata() const { return SnapshotMetadata(false, false); } bool exists() const { return false; } MapFieldValue GetData(DocumentSnapshot::ServerTimestampBehavior stb) const { return MapFieldValue{}; } FieldValue Get(const FieldPath& field, DocumentSnapshot::ServerTimestampBehavior stb) const { return FieldValue{}; } private: std::string id_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_DOCUMENT_SNAPSHOT_STUB_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_GEO_POINT_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_GEO_POINT_ANDROID_H_ #include <jni.h> #include "app/src/include/firebase/app.h" #include "firebase/firestore/geo_point.h" namespace firebase { namespace firestore { // This is the non-wrapper Android implementation of GeoPoint. Since GeoPoint // has most methods inlined, we use it directly instead of wrapping around a // Java GeoPoint object. We still need the helper functions to convert between // the two types. In addition, we also need proper initializer and terminator // for the Java class cache/uncache. class GeoPointInternal { public: using ApiType = GeoPoint; // Convert a C++ GeoPoint into a Java GeoPoint. static jobject GeoPointToJavaGeoPoint(JNIEnv* env, const GeoPoint& point); // Convert a Java GeoPoint into a C++ GeoPoint. static GeoPoint JavaGeoPointToGeoPoint(JNIEnv* env, jobject obj); // Gets the class object of Java GeoPoint class. static jclass GetClass(); private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_GEO_POINT_ANDROID_H_ <file_sep>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "app/instance_id/instance_id_desktop_impl.h" #include <assert.h> #include <algorithm> #include "app/instance_id/iid_data_generated.h" #include "app/rest/transport_curl.h" #include "app/rest/transport_interface.h" #include "app/rest/util.h" #include "app/rest/www_form_url_encoded.h" #include "app/src/app_common.h" #include "app/src/app_identifier.h" #include "app/src/base64.h" #include "app/src/callback.h" #include "app/src/cleanup_notifier.h" #include "app/src/locale.h" #include "app/src/time.h" #include "app/src/uuid.h" #include "flatbuffers/flexbuffers.h" #include "flatbuffers/stl_emulation.h" namespace firebase { namespace instance_id { namespace internal { using firebase::app::secure::UserSecureManager; using firebase::callback::NewCallback; // Response that signals this class when it's complete or canceled. class SignalSemaphoreResponse : public rest::Response { public: explicit SignalSemaphoreResponse(Semaphore* complete) : complete_(complete) {} void MarkCompleted() override { rest::Response::MarkCompleted(); complete_->Post(); } void MarkFailed() override { rest::Response::MarkFailed(); complete_->Post(); } void Wait() { complete_->Wait(); } private: Semaphore* complete_; }; // State for the current network operation. struct NetworkOperation { NetworkOperation(const std::string& request_data, Semaphore* complete) : request(request_data.c_str(), request_data.length()), response(complete) {} // Schedule the network operation. void Perform(rest::Transport* transport) { transport->Perform(request, &response, &controller); } // Cancel the current operation. void Cancel() { rest::Controller* ctrl = controller.get(); if (ctrl) ctrl->Cancel(); } // Data sent to the server. rest::Request request; // Data returned by the server. SignalSemaphoreResponse response; // Progress of the request and allows us to cancel the request. flatbuffers::unique_ptr<rest::Controller> controller; }; // Check-in backend. static const char kCheckinUrl[] = "https://device-provisioning.googleapis.com/checkin"; // Check-in refresh period (7 days) in milliseconds. static const uint64_t kCheckinRefreshPeriodMs = 7 * 24 * 60 * firebase::internal::kMillisecondsPerMinute; // Request type and protocol for check-in requests. static const int kCheckinRequestType = 2; static const int kCheckinProtocolVersion = 2; // Instance ID backend. static const char kInstanceIdUrl[] = "https://fcmtoken.googleapis.com/register"; // Backend had a temporary failure, the client should retry. http://b/27043795 static const char kPhoneRegistrationError[] = "PHONE_REGISTRATION_ERROR"; // Server detected the token is no longer valid. static const char kTokenResetError[] = "RST"; // Wildcard scope used to delete all tokens and the ID in a server registration. static const char kWildcardTokenScope[] = "*"; // Minimum retry time (in seconds) when a fetch token request fails. static const uint64_t kMinimumFetchTokenDelaySec = 30; // Maximum retry time (in seconds) when a fetch token request fails. static const uint64_t kMaximumFetchTokenDelaySec = 8 * firebase::internal::kMinutesPerHour * firebase::internal::kSecondsPerMinute; std::map<App*, InstanceIdDesktopImpl*> InstanceIdDesktopImpl::instance_id_by_app_; // NOLINT Mutex InstanceIdDesktopImpl::instance_id_by_app_mutex_; // NOLINT void InstanceIdDesktopImpl::FetchServerTokenCallback::Run() { bool retry; bool fetched_token = iid_->FetchServerToken(scope_.c_str(), &retry); if (fetched_token) { iid_->ref_future()->CompleteWithResult( future_handle_, kErrorNone, "", iid_->FindCachedToken(scope_.c_str())); } else if (retry) { // Retry with an expodential backoff. retry_delay_time_ = std::min(std::max(retry_delay_time_ * 2, kMinimumFetchTokenDelaySec), kMaximumFetchTokenDelaySec); iid_->scheduler_.Schedule(this, retry_delay_time_); } else { iid_->ref_future()->Complete(future_handle_, kErrorUnknownError, "FetchToken failed"); } } InstanceIdDesktopImpl::InstanceIdDesktopImpl(App* app) : storage_semaphore_(0), app_(app), locale_(firebase::internal::GetLocale()), logging_id_(rand()), // NOLINT ios_device_model_(app_common::kOperatingSystem), ios_device_version_("0.0.0" /* TODO */), app_version_("1.2.3" /* TODO */), os_version_(app_common::kOperatingSystem /* TODO add: version */), platform_(0), network_operation_complete_(0), terminating_(false) { rest::InitTransportCurl(); rest::util::Initialize(); transport_.reset(new rest::TransportCurl()); future_manager().AllocFutureApi(this, kInstanceIdFnCount); std::string package_name = app->options().package_name(); std::string project_id = app->options().project_id(); std::string app_identifier; user_secure_manager_ = MakeUnique<UserSecureManager>( "iid", firebase::internal::CreateAppIdentifierFromOptions(app_->options()) .c_str()); // Guarded through GetInstance() already. instance_id_by_app_[app] = this; // Cleanup this object if app is destroyed. CleanupNotifier* notifier = CleanupNotifier::FindByOwner(app); assert(notifier); notifier->RegisterObject(this, [](void* object) { // Since this is going to be shared by many other modules, ex. function and // instance_id, nothing should delete InstanceIdDesktopImpl until App is // deleted. // TODO(chkuang): Maybe reference count by module? InstanceIdDesktopImpl* instance_id_to_delete = reinterpret_cast<InstanceIdDesktopImpl*>(object); LogDebug( "InstanceIdDesktopImpl object 0x%08x is deleted when the App 0x%08x it " "depends upon is deleted.", static_cast<int>(reinterpret_cast<intptr_t>(instance_id_to_delete)), static_cast<int>( reinterpret_cast<intptr_t>(&instance_id_to_delete->app()))); delete instance_id_to_delete; }); } InstanceIdDesktopImpl::~InstanceIdDesktopImpl() { // Cancel any pending network operations. { MutexLock lock(network_operation_mutex_); // All outstanding operations should complete with an error. terminating_ = true; NetworkOperation* operation = network_operation_.get(); if (operation) operation->Cancel(); } // Cancel scheduled tasks and shut down the scheduler to prevent any // additional tasks being executed. scheduler_.CancelAllAndShutdownWorkerThread(); rest::CleanupTransportCurl(); rest::util::Terminate(); { MutexLock lock(instance_id_by_app_mutex_); auto it = instance_id_by_app_.find(app_); if (it == instance_id_by_app_.end()) return; assert(it->second == this); instance_id_by_app_.erase(it); } CleanupNotifier* notifier = CleanupNotifier::FindByOwner(app_); assert(notifier); notifier->UnregisterObject(this); } InstanceIdDesktopImpl* InstanceIdDesktopImpl::GetInstance(App* app) { #ifdef FIREBASE_EARLY_ACCESS_PREVIEW MutexLock lock(instance_id_by_app_mutex_); auto it = instance_id_by_app_.find(app); return it != instance_id_by_app_.end() ? it->second : new InstanceIdDesktopImpl(app); #else // Callers know that nullptr means "act as a stub". return nullptr; #endif // FIREBASE_EARLY_ACCESS_PREVIEW } Future<std::string> InstanceIdDesktopImpl::GetId() { // GetId() -> Check-in, generate an ID / get cached ID, return the ID SafeFutureHandle<std::string> handle = ref_future()->SafeAlloc<std::string>(kInstanceIdFnGetId); if (terminating_) { ref_future()->Complete(handle, kErrorShutdown, "Failed due to App shutdown in progress"); } else { auto callback = NewCallback( [](InstanceIdDesktopImpl* _this, SafeFutureHandle<std::string> _handle) { if (_this->InitialOrRefreshCheckin()) { _this->ref_future()->CompleteWithResult(_handle, kErrorNone, "", _this->instance_id_); } else { _this->ref_future()->Complete(_handle, kErrorUnavailable, "Error in checkin"); } }, this, handle); scheduler_.Schedule(callback); } return MakeFuture(ref_future(), handle); } Future<std::string> InstanceIdDesktopImpl::GetIdLastResult() { return static_cast<const Future<std::string>&>( ref_future()->LastResult(kInstanceIdFnGetId)); } Future<void> InstanceIdDesktopImpl::DeleteId() { // DeleteId() -> Delete all tokens and remove them from the cache, then clear // ID. SafeFutureHandle<void> handle = ref_future()->SafeAlloc<void>(kInstanceIdFnRemoveId); if (terminating_) { ref_future()->Complete(handle, kErrorShutdown, "Failed due to App shutdown in progress"); } else { auto callback = NewCallback( [](InstanceIdDesktopImpl* _this, SafeFutureHandle<void> _handle) { if (_this->DeleteServerToken(nullptr, true)) { _this->ref_future()->Complete(_handle, kErrorNone, ""); } else { _this->ref_future()->Complete(_handle, kErrorUnknownError, "DeleteId failed"); } }, this, handle); scheduler_.Schedule(callback); } return MakeFuture(ref_future(), handle); } Future<void> InstanceIdDesktopImpl::DeleteIdLastResult() { return static_cast<const Future<void>&>( ref_future()->LastResult(kInstanceIdFnRemoveId)); } Future<std::string> InstanceIdDesktopImpl::GetToken(const char* scope) { // GetToken() -> GetId() then get token from cache or using check-in // information, return the token SafeFutureHandle<std::string> handle = ref_future()->SafeAlloc<std::string>(kInstanceIdFnGetToken); if (terminating_) { ref_future()->Complete(handle, kErrorShutdown, "Failed due to App shutdown in progress"); } else { scheduler_.Schedule(new FetchServerTokenCallback(this, scope, handle)); } return MakeFuture(ref_future(), handle); } Future<std::string> InstanceIdDesktopImpl::GetTokenLastResult() { return static_cast<const Future<std::string>&>( ref_future()->LastResult(kInstanceIdFnGetToken)); } Future<void> InstanceIdDesktopImpl::DeleteToken(const char* scope) { // DeleteToken() --> delete token request and remove from the cache SafeFutureHandle<void> handle = ref_future()->SafeAlloc<void>(kInstanceIdFnRemoveToken); if (terminating_) { ref_future()->Complete(handle, kErrorShutdown, "Failed due to App shutdown in progress"); } else { std::string scope_str(scope); auto callback = NewCallback( [](InstanceIdDesktopImpl* _this, std::string _scope_str, SafeFutureHandle<void> _handle) { if (_this->DeleteServerToken(_scope_str.c_str(), false)) { _this->ref_future()->Complete(_handle, kErrorNone, ""); } else { _this->ref_future()->Complete(_handle, kErrorUnknownError, "DeleteToken failed"); } }, this, scope_str, handle); scheduler_.Schedule(callback); } return MakeFuture(ref_future(), handle); } Future<void> InstanceIdDesktopImpl::DeleteTokenLastResult() { return static_cast<const Future<void>&>( ref_future()->LastResult(kInstanceIdFnRemoveToken)); } // Save the instance ID to local secure storage. bool InstanceIdDesktopImpl::SaveToStorage() { if (terminating_) return false; // Build up a serialized buffer algorithmically: flatbuffers::FlatBufferBuilder builder; std::vector<flatbuffers::Offset<Token>> token_offsets; for (auto it = tokens_.begin(); it != tokens_.end(); ++it) { token_offsets.push_back(CreateTokenDirect(builder, it->first.c_str() /* scope */, it->second.c_str() /* token */)); } auto iid_data_table = CreateInstanceIdDesktopDataDirect( builder, instance_id_.c_str(), checkin_data_.device_id.c_str(), checkin_data_.security_token.c_str(), checkin_data_.digest.c_str(), checkin_data_.last_checkin_time_ms, &token_offsets); builder.Finish(iid_data_table); std::string save_string; auto bufferpointer = reinterpret_cast<const char*>(builder.GetBufferPointer()); save_string.assign(bufferpointer, bufferpointer + builder.GetSize()); // Encode flatbuffer std::string encoded; UserSecureManager::BinaryToAscii(save_string, &encoded); Future<void> future = user_secure_manager_->SaveUserData(app_->name(), encoded); future.OnCompletion( [](const Future<void>& result, void* sem_void) { Semaphore* sem_ptr = reinterpret_cast<Semaphore*>(sem_void); sem_ptr->Post(); }, &storage_semaphore_); storage_semaphore_.Wait(); return future.error() == 0; } // Load the instance ID from local secure storage. bool InstanceIdDesktopImpl::LoadFromStorage() { Future<std::string> future = user_secure_manager_->LoadUserData(app_->name()); future.OnCompletion( [](const Future<std::string>& result, void* sem_void) { Semaphore* sem_ptr = reinterpret_cast<Semaphore*>(sem_void); sem_ptr->Post(); }, &storage_semaphore_); storage_semaphore_.Wait(); if (future.error() == 0) { ReadStoredInstanceIdData(*future.result()); } return future.error() == 0; } // Delete the instance ID from local secure storage. bool InstanceIdDesktopImpl::DeleteFromStorage() { if (terminating_) return false; Future<void> future = user_secure_manager_->DeleteUserData(app_->name()); future.OnCompletion( [](const Future<void>& result, void* sem_void) { Semaphore* sem_ptr = reinterpret_cast<Semaphore*>(sem_void); sem_ptr->Post(); }, &storage_semaphore_); storage_semaphore_.Wait(); return future.error() == 0; } // Returns true if data was successfully read. bool InstanceIdDesktopImpl::ReadStoredInstanceIdData( const std::string& loaded_string) { // Decode to flatbuffer std::string decoded; if (!UserSecureManager::AsciiToBinary(loaded_string, &decoded)) { LogWarning("Error decoding saved Instance ID."); return false; } // Verify the Flatbuffer is valid. flatbuffers::Verifier verifier( reinterpret_cast<const uint8_t*>(decoded.c_str()), decoded.length()); if (!VerifyInstanceIdDesktopDataBuffer(verifier)) { LogWarning("Error verifying saved Instance ID."); return false; } auto iid_data_fb = GetInstanceIdDesktopData(decoded.c_str()); if (iid_data_fb == nullptr) { LogWarning("Error reading table for saved Instance ID."); return false; } instance_id_ = iid_data_fb->instance_id()->c_str(); checkin_data_.device_id = iid_data_fb->device_id()->c_str(); checkin_data_.security_token = iid_data_fb->security_token()->c_str(); checkin_data_.digest = iid_data_fb->digest()->c_str(); checkin_data_.last_checkin_time_ms = iid_data_fb->last_checkin_time_ms(); tokens_.clear(); auto fbtokens = iid_data_fb->tokens(); for (auto it = fbtokens->begin(); it != fbtokens->end(); ++it) { tokens_[it->scope()->c_str()] = it->token()->c_str(); } return true; } bool InstanceIdDesktopImpl::InitialOrRefreshCheckin() { if (terminating_) return false; // Load check-in data from storage if it hasn't already been loaded. if (checkin_data_.last_checkin_time_ms == 0) { // Try loading from storage. Since we can't tell whether this failed // because the data doesn't exist or if there is an I/O error, just // continue. LoadFromStorage(); } // If we don't have an instance_id_ yet, generate one now. if (instance_id_.empty()) { instance_id_ = GenerateAppId(); } if (checkin_data_.device_id.empty() || checkin_data_.security_token.empty() || checkin_data_.digest.empty()) { // If any of these aren't set, checkin data is incomplete, so clear it. checkin_data_.Clear(); } // If we've already checked in. if (checkin_data_.last_checkin_time_ms > 0) { // Make sure the device ID and token aren't expired. uint64_t time_elapsed_ms = firebase::internal::GetTimestamp() - checkin_data_.last_checkin_time_ms; if (time_elapsed_ms < kCheckinRefreshPeriodMs) { // Everything is up to date. return true; } checkin_data_.Clear(); } // Construct the JSON request. flexbuffers::Builder fbb; struct BuilderScope { BuilderScope(flexbuffers::Builder* fbb_, const CheckinData* checkin_data_, const char* locale_, const char* timezone_, int logging_id_, const char* ios_device_model_, const char* ios_device_version_) : fbb(fbb_), checkin_data(checkin_data_), locale(locale_), timezone(timezone_), logging_id(logging_id_), ios_device_model(ios_device_model_), ios_device_version(ios_device_version_) {} flexbuffers::Builder* fbb; const CheckinData* checkin_data; const char* locale; const char* timezone; int logging_id; const char* ios_device_model; const char* ios_device_version; } builder_scope(&fbb, &checkin_data_, locale_.c_str(), timezone_.empty() ? firebase::internal::GetTimezone().c_str() : timezone_.c_str(), logging_id_, ios_device_model_.c_str(), ios_device_version_.c_str()); fbb.Map( [](BuilderScope& builder_scope) { flexbuffers::Builder* fbb = builder_scope.fbb; const CheckinData& checkin_data = *builder_scope.checkin_data; fbb->Map( "checkin", [](BuilderScope& builder_scope) { flexbuffers::Builder* fbb = builder_scope.fbb; const CheckinData& checkin_data = *builder_scope.checkin_data; fbb->Map( "iosbuild", [](BuilderScope& builder_scope) { flexbuffers::Builder* fbb = builder_scope.fbb; fbb->String("model", builder_scope.ios_device_model); fbb->String("os_version", builder_scope.ios_device_version); }, builder_scope); fbb->Int("type", kCheckinRequestType); fbb->Int("user_number", 0 /* unused at the moment */); fbb->Int("last_checkin_msec", checkin_data.last_checkin_time_ms); }, builder_scope); fbb->Int("fragment", 0 /* unused at the moment */); fbb->Int("logging_id", builder_scope.logging_id); fbb->String("locale", builder_scope.locale); fbb->Int("version", kCheckinProtocolVersion); fbb->String("digest", checkin_data.digest.c_str()); fbb->String("timezone", builder_scope.timezone); fbb->Int("user_serial_number", 0 /* unused at the moment */); fbb->Int("id", flatbuffers::StringToInt(checkin_data.device_id.c_str())); fbb->Int("security_token", flatbuffers::StringToInt(checkin_data.security_token.c_str())); }, builder_scope); fbb.Finish(); request_buffer_.clear(); flexbuffers::GetRoot(fbb.GetBuffer()).ToString(true, true, request_buffer_); // Send request to the server then wait for the response or for the request // to be canceled by another thread. { MutexLock lock(network_operation_mutex_); network_operation_.reset( new NetworkOperation(request_buffer_, &network_operation_complete_)); rest::Request* request = &network_operation_->request; request->set_url(kCheckinUrl); request->set_method(rest::util::kPost); request->add_header(rest::util::kAccept, rest::util::kApplicationJson); request->add_header(rest::util::kContentType, rest::util::kApplicationJson); network_operation_->Perform(transport_.get()); } network_operation_complete_.Wait(); logging_id_ = rand(); // NOLINT { MutexLock lock(network_operation_mutex_); assert(network_operation_.get()); const rest::Response& response = network_operation_->response; // Check for errors if (response.status() != rest::util::HttpSuccess) { LogError("Check-in failed with response %d '%s'", response.status(), response.GetBody()); network_operation_.reset(nullptr); return false; } // Parse the response. flexbuffers::Builder fbb; flatbuffers::Parser parser; if (!parser.ParseFlexBuffer(response.GetBody(), nullptr, &fbb)) { LogError("Unable to parse response '%s'", response.GetBody()); network_operation_.reset(nullptr); return false; } auto root = flexbuffers::GetRoot(fbb.GetBuffer()).AsMap(); if (!root["stats_ok"].AsBool()) { LogError("Unexpected stats_ok field '%s' vs 'true'", root["stats_ok"].ToString().c_str()); network_operation_.reset(nullptr); return false; } checkin_data_.device_id = root["android_id"].ToString(); checkin_data_.security_token = root["security_token"].ToString(); checkin_data_.digest = root["digest"].AsString().c_str(); checkin_data_.last_checkin_time_ms = firebase::internal::GetTimestamp(); network_operation_.reset(nullptr); if (!SaveToStorage()) { checkin_data_.Clear(); LogError("Unable to save check-in information to storage."); return false; } } return true; } std::string InstanceIdDesktopImpl::GenerateAppId() { firebase::internal::Uuid uuid; uuid.Generate(); // Collapse into 8 bytes, forcing the top 4 bits to be 0x70. uint8_t buffer[8]; buffer[0] = ((uuid.data[0] ^ uuid.data[8]) & 0x0f) | 0x70; buffer[1] = uuid.data[1] ^ uuid.data[9]; buffer[2] = uuid.data[2] ^ uuid.data[10]; buffer[3] = uuid.data[3] ^ uuid.data[11]; buffer[4] = uuid.data[4] ^ uuid.data[12]; buffer[5] = uuid.data[5] ^ uuid.data[13]; buffer[6] = uuid.data[6] ^ uuid.data[14]; buffer[7] = uuid.data[7] ^ uuid.data[15]; std::string input(reinterpret_cast<char*>(buffer), sizeof(buffer)); std::string output; if (firebase::internal::Base64EncodeUrlSafe(input, &output)) { return output; } return ""; // Error encoding. } std::string InstanceIdDesktopImpl::FindCachedToken(const char* scope) { auto cached_token = tokens_.find(scope); if (cached_token == tokens_.end()) return std::string(); return cached_token->second; } void InstanceIdDesktopImpl::DeleteCachedToken(const char* scope) { auto cached_token = tokens_.find(scope); if (cached_token != tokens_.end()) tokens_.erase(cached_token); } void InstanceIdDesktopImpl::ServerTokenOperation( const char* scope, void (*request_callback)(rest::Request* request, void* state), void* state) { const AppOptions& app_options = app_->options(); request_buffer_.clear(); rest::WwwFormUrlEncoded form(&request_buffer_); form.Add("sender", app_options.messaging_sender_id()); form.Add("app", app_options.package_name()); form.Add("app_ver", app_version_.c_str()); form.Add("device", checkin_data_.device_id.c_str()); // NOTE: We're not providing the Xcliv field here as we don't support // FCM on desktop yet. form.Add("X-scope", scope); form.Add("X-subtype", app_options.messaging_sender_id()); form.Add("X-osv", os_version_.c_str()); form.Add("plat", flatbuffers::NumToString(platform_).c_str()); form.Add("app_id", instance_id_.c_str()); // Send request to the server then wait for the response or for the request // to be canceled by another thread. { MutexLock lock(network_operation_mutex_); network_operation_.reset( new NetworkOperation(request_buffer_, &network_operation_complete_)); rest::Request* request = &network_operation_->request; request->set_url(kInstanceIdUrl); request->set_method(rest::util::kPost); request->add_header(rest::util::kAccept, rest::util::kApplicationWwwFormUrlencoded); request->add_header(rest::util::kContentType, rest::util::kApplicationWwwFormUrlencoded); request->add_header(rest::util::kAuthorization, (std::string("AidLogin ") + checkin_data_.device_id + std::string(":") + checkin_data_.security_token) .c_str()); if (request_callback) request_callback(request, state); network_operation_->Perform(transport_.get()); } network_operation_complete_.Wait(); } bool InstanceIdDesktopImpl::FetchServerToken(const char* scope, bool* retry) { *retry = false; if (terminating_ || !InitialOrRefreshCheckin()) return false; // If we already have a token, don't refresh. std::string token = FindCachedToken(scope); if (!token.empty()) return true; ServerTokenOperation(scope, nullptr, nullptr); { MutexLock lock(network_operation_mutex_); assert(network_operation_.get()); const rest::Response& response = network_operation_->response; // Check for errors if (response.status() != rest::util::HttpSuccess) { LogError("Instance ID token fetch failed with response %d '%s'", response.status(), response.GetBody()); network_operation_.reset(nullptr); return false; } // Parse the response. auto form_data = rest::WwwFormUrlEncoded::Parse(response.GetBody()); std::string error; // Search the response for a token or an error. for (size_t i = 0; i < form_data.size(); ++i) { const auto& item = form_data[i]; if (item.key == "token") { token = item.value; } else if (item.key == "Error") { error = item.value; } } // Parse any returned errors. if (!error.empty()) { size_t component_start = 0; size_t component_end; do { component_end = error.find(":", component_start); std::string error_component = error.substr(component_start, component_end - component_start); if (error_component == kPhoneRegistrationError) { network_operation_.reset(nullptr); *retry = true; return false; } else if (error_component == kTokenResetError) { // Server requests that the token is reset. DeleteServerToken(nullptr, true); network_operation_.reset(nullptr); return false; } component_start = component_end + 1; } while (component_end != std::string::npos); } if (token.empty()) { LogError( "No token returned in instance ID token fetch. " "Responded with '%s'", response.GetBody()); network_operation_.reset(nullptr); return false; } // Cache the token. tokens_[scope] = token; network_operation_.reset(nullptr); } if (!SaveToStorage()) { LogError("Failed to save token for scope %s to storage", scope); return false; } return true; } bool InstanceIdDesktopImpl::DeleteServerToken(const char* scope, bool delete_id) { if (terminating_) return false; // Load credentials from storage as we'll need them to delete the ID. LoadFromStorage(); if (delete_id) { if (tokens_.empty() && instance_id_.empty()) return true; scope = kWildcardTokenScope; } else { // If we don't have a token, we have nothing to do. std::string token = FindCachedToken(scope); if (token.empty()) return true; } ServerTokenOperation( scope, [](rest::Request* request, void* delete_id) { std::string body; request->ReadBodyIntoString(&body); rest::WwwFormUrlEncoded form(&body); form.Add("delete", "true"); if (delete_id) form.Add("iid-operation", "delete"); request->set_post_fields(body.c_str(), body.length()); }, reinterpret_cast<void*>(delete_id ? 1 : 0)); { MutexLock lock(network_operation_mutex_); assert(network_operation_.get()); const rest::Response& response = network_operation_->response; // Check for errors if (response.status() != rest::util::HttpSuccess) { LogError("Instance ID token delete failed with response %d '%s'", response.status(), response.GetBody()); network_operation_.reset(nullptr); return false; } // Parse the response. auto form_data = rest::WwwFormUrlEncoded::Parse(response.GetBody()); bool found_valid_response = false; for (int i = 0; i < form_data.size(); ++i) { const auto& item = form_data[i]; if (item.key == "deleted" || item.key == "token") { found_valid_response = true; break; } } if (found_valid_response) { if (delete_id) { checkin_data_.Clear(); instance_id_.clear(); tokens_.clear(); DeleteFromStorage(); } else { DeleteCachedToken(scope); if (!SaveToStorage()) { LogError("Failed to delete tokens for scope %s from storage", scope); network_operation_.reset(nullptr); return false; } } } else { LogError( "Instance ID token delete failed, server returned invalid " "response '%s'", response.GetBody()); network_operation_.reset(nullptr); } return found_valid_response; } } } // namespace internal } // namespace instance_id } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_DOCUMENT_SNAPSHOT_IOS_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_DOCUMENT_SNAPSHOT_IOS_H_ #include <memory> #include <string> #include <vector> #include "firestore/src/include/firebase/firestore/document_reference.h" #include "firestore/src/include/firebase/firestore/document_snapshot.h" #include "firestore/src/include/firebase/firestore/field_value.h" #include "firestore/src/include/firebase/firestore/map_field_value.h" #include "firestore/src/include/firebase/firestore/snapshot_metadata.h" #include "firestore/src/ios/firestore_ios.h" #include "Firestore/core/src/firebase/firestore/api/document_snapshot.h" #include "Firestore/core/src/firebase/firestore/model/field_value.h" namespace firebase { namespace firestore { class Firestore; class FirestoreInternal; class DocumentSnapshotInternal { public: explicit DocumentSnapshotInternal(api::DocumentSnapshot&& snapshot); Firestore* firestore(); FirestoreInternal* firestore_internal(); const FirestoreInternal* firestore_internal() const; const std::string& id() const; bool exists() const; SnapshotMetadata metadata() const; MapFieldValue GetData(DocumentSnapshot::ServerTimestampBehavior stb) const; FieldValue Get(const FieldPath& field, DocumentSnapshot::ServerTimestampBehavior stb) const; const api::DocumentSnapshot& document_snapshot_core() const { return snapshot_; } // Unimplemented DocumentReference reference() const; private: using ServerTimestampBehavior = DocumentSnapshot::ServerTimestampBehavior; FieldValue GetValue(const model::FieldPath& path, ServerTimestampBehavior stb) const; // Note: these are member functions only because access to `api::Firestore` // is needed to create a `DocumentReferenceInternal`. FieldValue ConvertAnyValue(const model::FieldValue& input, ServerTimestampBehavior stb) const; FieldValue ConvertObject(const model::FieldValue::Map& object, ServerTimestampBehavior stb) const; FieldValue ConvertArray(const model::FieldValue::Array& array, ServerTimestampBehavior stb) const; FieldValue ConvertReference( const model::FieldValue::Reference& reference) const; FieldValue ConvertServerTimestamp( const model::FieldValue::ServerTimestamp& server_timestamp, ServerTimestampBehavior stb) const; FieldValue ConvertScalar(const model::FieldValue& scalar, ServerTimestampBehavior stb) const; api::DocumentSnapshot snapshot_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_DOCUMENT_SNAPSHOT_IOS_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_TESTS_UTIL_EVENT_ACCUMULATOR_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_TESTS_UTIL_EVENT_ACCUMULATOR_H_ #include "firestore/src/tests/firestore_integration_test.h" namespace firebase { namespace firestore { // Event accumulator for integration test. Ported from the native SDKs. template <typename T> class EventAccumulator { public: EventAccumulator() : listener_("EventAccumulator") {} TestEventListener<T>* listener() { return &listener_; } std::vector<T> Await(int num_events) { max_events_ += num_events; FirestoreIntegrationTest::Await(listener_, max_events_); EXPECT_EQ(Error::Ok, listener_.first_error()); std::vector<T> result; // We cannot use listener.last_result() as it goes backward and can // contains more than max_events_ events. So we look up manually. for (int i = max_events_ - num_events; i < max_events_; ++i) { result.push_back(listener_.last_result_[i]); } return result; } /** Await 1 event. */ T Await() { return Await(1)[0]; } /** Waits for a snapshot with pending writes. */ T AwaitLocalEvent() { T event; do { event = Await(); } while (!HasPendingWrites(event)); return event; } /** Waits for a snapshot that has no pending writes. */ T AwaitRemoteEvent() { T event; do { event = Await(); } while (HasPendingWrites(event)); return event; } /** * Waits for a snapshot that is from cache. * NOTE: Helper exists only in C++ test. Not in native SDK test yet. */ T AwaitCacheEvent() { T event; do { event = Await(); } while (!IsFromCache(event)); return event; } /** * Waits for a snapshot that is not from cache. * NOTE: Helper exists only in C++ test. Not in native SDK test yet. */ T AwaitServerEvent() { T event; do { event = Await(); } while (IsFromCache(event)); return event; } private: bool HasPendingWrites(T event) { return event.metadata().has_pending_writes(); } bool IsFromCache(T event) { return event.metadata().is_from_cache(); } TestEventListener<T> listener_; int max_events_ = 0; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_TESTS_UTIL_EVENT_ACCUMULATOR_H_ <file_sep>#include "firestore/src/common/wrapper_assertions.h" namespace firebase { namespace firestore { namespace testutil { #if defined(__ANDROID__) template <> ListenerRegistrationInternal* NewInternal<ListenerRegistrationInternal>() { return nullptr; } #endif // defined(__ANDROID__) } // namespace testutil } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_SERVER_TIMESTAMP_BEHAVIOR_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_SERVER_TIMESTAMP_BEHAVIOR_ANDROID_H_ #include <map> #include "app/src/include/firebase/app.h" #include "app/src/util_android.h" #include "firestore/src/include/firebase/firestore/document_snapshot.h" namespace firebase { namespace firestore { class ServerTimestampBehaviorInternal { public: static jobject ToJavaObject(JNIEnv* env, DocumentSnapshot::ServerTimestampBehavior stb); private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); static std::map<DocumentSnapshot::ServerTimestampBehavior, jobject>* cpp_enum_to_java_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_SERVER_TIMESTAMP_BEHAVIOR_ANDROID_H_ <file_sep>#include "firestore/src/android/field_value_android.h" #include <jni.h> #include "app/meta/move.h" #include "app/src/util_android.h" #include "firestore/src/android/blob_android.h" #include "firestore/src/android/document_reference_android.h" #include "firestore/src/android/geo_point_android.h" #include "firestore/src/android/timestamp_android.h" #include "firestore/src/android/util_android.h" namespace firebase { namespace firestore { using Type = FieldValue::Type; // com.google.firebase.firestore.FieldValue is the public type which contains // static methods to build sentinel values. // clang-format off #define FIELD_VALUE_METHODS(X) \ X(Delete, "delete", "()Lcom/google/firebase/firestore/FieldValue;", \ util::kMethodTypeStatic), \ X(ServerTimestamp, "serverTimestamp", \ "()Lcom/google/firebase/firestore/FieldValue;", util::kMethodTypeStatic), \ X(ArrayUnion, "arrayUnion", \ "([Ljava/lang/Object;)Lcom/google/firebase/firestore/FieldValue;", \ util::kMethodTypeStatic), \ X(ArrayRemove, "arrayRemove", \ "([Ljava/lang/Object;)Lcom/google/firebase/firestore/FieldValue;", \ util::kMethodTypeStatic) // clang-format on METHOD_LOOKUP_DECLARATION(field_value, FIELD_VALUE_METHODS) METHOD_LOOKUP_DEFINITION(field_value, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/FieldValue", FIELD_VALUE_METHODS) jobject FieldValueInternal::delete_ = nullptr; jobject FieldValueInternal::server_timestamp_ = nullptr; FieldValueInternal::FieldValueInternal(FirestoreInternal* firestore, jobject obj) : Wrapper(firestore, obj, AllowNullObject::Yes), cached_type_(Type::kNull) {} FieldValueInternal::FieldValueInternal(const FieldValueInternal& wrapper) : Wrapper(wrapper), cached_type_(wrapper.cached_type_), cached_blob_(wrapper.cached_blob_) {} FieldValueInternal::FieldValueInternal(FieldValueInternal&& wrapper) : Wrapper(firebase::Move(wrapper)), cached_type_(wrapper.cached_type_), cached_blob_(wrapper.cached_blob_) {} FieldValueInternal::FieldValueInternal() : cached_type_(Type::kNull) { // The null Java object is actually represented by a nullptr jobject value. obj_ = nullptr; } FieldValueInternal::FieldValueInternal(bool value) : Wrapper( util::boolean_class::GetClass(), util::boolean_class::GetMethodId(util::boolean_class::kConstructor), static_cast<jboolean>(value)), cached_type_(Type::kBoolean) {} FieldValueInternal::FieldValueInternal(int64_t value) : Wrapper(util::long_class::GetClass(), util::long_class::GetMethodId(util::long_class::kConstructor), static_cast<jlong>(value)), cached_type_(Type::kInteger) {} FieldValueInternal::FieldValueInternal(double value) : Wrapper(util::double_class::GetClass(), util::double_class::GetMethodId(util::double_class::kConstructor), static_cast<jdouble>(value)), cached_type_(Type::kDouble) {} FieldValueInternal::FieldValueInternal(Timestamp value) : cached_type_(Type::kTimestamp) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject obj = TimestampInternal::TimestampToJavaTimestamp(env, value); obj_ = env->NewGlobalRef(obj); env->DeleteLocalRef(obj); } FieldValueInternal::FieldValueInternal(std::string value) : cached_type_(Type::kString) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject str = env->NewStringUTF(value.c_str()); obj_ = env->NewGlobalRef(str); env->DeleteLocalRef(str); CheckAndClearJniExceptions(env); FIREBASE_ASSERT(obj_ != nullptr); } // We do not initialize cached_blob_ with value here as the instance constructed // with const uint8_t* is generally used for updating Firestore while // cached_blob_ is only needed when reading from Firestore and calling with // blob_value(). FieldValueInternal::FieldValueInternal(const uint8_t* value, size_t size) : cached_type_(Type::kBlob) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject obj = BlobInternal::BlobToJavaBlob(env, value, size); obj_ = env->NewGlobalRef(obj); env->DeleteLocalRef(obj); CheckAndClearJniExceptions(env); FIREBASE_ASSERT(obj_ != nullptr); } FieldValueInternal::FieldValueInternal(DocumentReference value) : Wrapper(value.internal_), cached_type_{Type::kReference} {} FieldValueInternal::FieldValueInternal(GeoPoint value) : cached_type_(Type::kGeoPoint) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject obj = GeoPointInternal::GeoPointToJavaGeoPoint(env, value); obj_ = env->NewGlobalRef(obj); env->DeleteLocalRef(obj); } FieldValueInternal::FieldValueInternal(std::vector<FieldValue> value) : Wrapper( util::array_list::GetClass(), util::array_list::GetMethodId(util::array_list::kConstructorWithSize), static_cast<jint>(value.size())), cached_type_(Type::kArray) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jmethodID add_method = util::array_list::GetMethodId(util::array_list::kAdd); for (const FieldValue& element : value) { // ArrayList.Add() always returns true, which we have no use for. // TODO(b/150016438): don't conflate invalid `FieldValue`s and null. env->CallBooleanMethod(obj_, add_method, TryGetJobject(element)); } CheckAndClearJniExceptions(env); } FieldValueInternal::FieldValueInternal(MapFieldValue value) : Wrapper(util::hash_map::GetClass(), util::hash_map::GetMethodId(util::hash_map::kConstructor)), cached_type_(Type::kMap) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jmethodID put_method = util::map::GetMethodId(util::map::kPut); for (const auto& kv : value) { jobject key = env->NewStringUTF(kv.first.c_str()); // Map::Put() returns previously associated value or null, which we have no // use for. // TODO(b/150016438): don't conflate invalid `FieldValue`s and null. env->CallObjectMethod(obj_, put_method, key, TryGetJobject(kv.second)); env->DeleteLocalRef(key); } CheckAndClearJniExceptions(env); } Type FieldValueInternal::type() const { if (cached_type_ != Type::kNull) { return cached_type_; } if (obj_ == nullptr) { return Type::kNull; } // We do not have any knowledge on the type yet. Check the runtime type with // each known type. JNIEnv* env = firestore_->app()->GetJNIEnv(); if (env->IsInstanceOf(obj_, util::boolean_class::GetClass())) { cached_type_ = Type::kBoolean; return Type::kBoolean; } if (env->IsInstanceOf(obj_, util::long_class::GetClass())) { cached_type_ = Type::kInteger; return Type::kInteger; } if (env->IsInstanceOf(obj_, util::double_class::GetClass())) { cached_type_ = Type::kDouble; return Type::kDouble; } if (env->IsInstanceOf(obj_, TimestampInternal::GetClass())) { cached_type_ = Type::kTimestamp; return Type::kTimestamp; } if (env->IsInstanceOf(obj_, util::string::GetClass())) { cached_type_ = Type::kString; return Type::kString; } if (env->IsInstanceOf(obj_, BlobInternal::GetClass())) { cached_type_ = Type::kBlob; return Type::kBlob; } if (env->IsInstanceOf(obj_, DocumentReferenceInternal::GetClass())) { cached_type_ = Type::kReference; return Type::kReference; } if (env->IsInstanceOf(obj_, GeoPointInternal::GetClass())) { cached_type_ = Type::kGeoPoint; return Type::kGeoPoint; } if (env->IsInstanceOf(obj_, util::list::GetClass())) { cached_type_ = Type::kArray; return Type::kArray; } if (env->IsInstanceOf(obj_, util::map::GetClass())) { cached_type_ = Type::kMap; return Type::kMap; } FIREBASE_ASSERT_MESSAGE(false, "Unsupported FieldValue type: %s", util::JObjectClassName(env, obj_).c_str()); return Type::kNull; } bool FieldValueInternal::boolean_value() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); // Make sure this instance is of correct type. if (cached_type_ == Type::kNull) { FIREBASE_ASSERT(env->IsInstanceOf(obj_, util::boolean_class::GetClass())); cached_type_ = Type::kBoolean; } else { FIREBASE_ASSERT(cached_type_ == Type::kBoolean); } return util::JBooleanToBool(env, obj_); } int64_t FieldValueInternal::integer_value() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); // Make sure this instance is of correct type. if (cached_type_ == Type::kNull) { FIREBASE_ASSERT(env->IsInstanceOf(obj_, util::long_class::GetClass())); cached_type_ = Type::kInteger; } else { FIREBASE_ASSERT(cached_type_ == Type::kInteger); } return util::JLongToInt64(env, obj_); } double FieldValueInternal::double_value() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); // Make sure this instance is of correct type. if (cached_type_ == Type::kNull) { FIREBASE_ASSERT(env->IsInstanceOf(obj_, util::double_class::GetClass())); cached_type_ = Type::kDouble; } else { FIREBASE_ASSERT(cached_type_ == Type::kDouble); } return util::JDoubleToDouble(env, obj_); } Timestamp FieldValueInternal::timestamp_value() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); // Make sure this instance is of correct type. if (cached_type_ == Type::kNull) { FIREBASE_ASSERT(env->IsInstanceOf(obj_, TimestampInternal::GetClass())); cached_type_ = Type::kTimestamp; } else { FIREBASE_ASSERT(cached_type_ == Type::kTimestamp); } return TimestampInternal::JavaTimestampToTimestamp(env, obj_); } std::string FieldValueInternal::string_value() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); // Make sure this instance is of correct type. if (cached_type_ == Type::kNull) { FIREBASE_ASSERT(env->IsInstanceOf(obj_, util::string::GetClass())); cached_type_ = Type::kString; } else { FIREBASE_ASSERT(cached_type_ == Type::kString); } return util::JStringToString(env, obj_); } const uint8_t* FieldValueInternal::blob_value() const { if (blob_size() == 0) { // Doesn't matter what we return. Not return &(cached_blob_.get()->front()) // to avoid going into undefined-behavior world. Once we drop the support of // STLPort, we might just combine this case into the logic below by calling // cached_blob_.get()->data(). return nullptr; } if (cached_blob_.get()) { return &(cached_blob_.get()->front()); } size_t size = blob_size(); // firebase::SharedPtr does not have set() API. cached_blob_ = SharedPtr<std::vector<uint8_t>>{new std::vector<uint8_t>(size)}; JNIEnv* env = firestore_->app()->GetJNIEnv(); jbyteArray bytes = BlobInternal::JavaBlobToJbyteArray(env, obj_); static_assert(sizeof(uint8_t) == sizeof(jbyte), "uint8_t and jbyte must be of same size"); env->GetByteArrayRegion( bytes, 0, size, reinterpret_cast<jbyte*>(&(cached_blob_.get()->front()))); env->DeleteLocalRef(bytes); CheckAndClearJniExceptions(env); return &(cached_blob_.get()->front()); } size_t FieldValueInternal::blob_size() const { if (cached_blob_.get()) { return cached_blob_.get()->size(); } JNIEnv* env = firestore_->app()->GetJNIEnv(); // Make sure this instance is of correct type. if (cached_type_ == Type::kNull) { FIREBASE_ASSERT(env->IsInstanceOf(obj_, BlobInternal::GetClass())); cached_type_ = Type::kBlob; } else { FIREBASE_ASSERT(cached_type_ == Type::kBlob); } jbyteArray bytes = BlobInternal::JavaBlobToJbyteArray(env, obj_); jsize result = env->GetArrayLength(bytes); env->DeleteLocalRef(bytes); CheckAndClearJniExceptions(env); return static_cast<size_t>(result); } DocumentReference FieldValueInternal::reference_value() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); // Make sure this instance is of correct type. if (cached_type_ == Type::kNull) { FIREBASE_ASSERT( env->IsInstanceOf(obj_, DocumentReferenceInternal::GetClass())); cached_type_ = Type::kReference; } else { FIREBASE_ASSERT(cached_type_ == Type::kReference); } if (!obj_) { // Reference may be invalid. return DocumentReference{}; } return DocumentReference{new DocumentReferenceInternal(firestore_, obj_)}; } GeoPoint FieldValueInternal::geo_point_value() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); // Make sure this instance is of correct type. if (cached_type_ == Type::kNull) { FIREBASE_ASSERT(env->IsInstanceOf(obj_, GeoPointInternal::GetClass())); cached_type_ = Type::kGeoPoint; } else { FIREBASE_ASSERT(cached_type_ == Type::kGeoPoint); } return GeoPointInternal::JavaGeoPointToGeoPoint(env, obj_); } std::vector<FieldValue> FieldValueInternal::array_value() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); // Make sure this instance is of correct type. if (cached_type_ == Type::kNull) { FIREBASE_ASSERT(env->IsInstanceOf(obj_, util::list::GetClass())); cached_type_ = Type::kArray; } else { FIREBASE_ASSERT(cached_type_ == Type::kArray); } std::vector<FieldValue> result; jint size = env->CallIntMethod(obj_, util::list::GetMethodId(util::list::kSize)); result.reserve(size); CheckAndClearJniExceptions(env); for (jint i = 0; i < size; ++i) { jobject element = env->CallObjectMethod( obj_, util::list::GetMethodId(util::list::kGet), i); // Cannot call emplace_back as the constructor is protected. result.push_back(FieldValue(new FieldValueInternal(firestore_, element))); env->DeleteLocalRef(element); CheckAndClearJniExceptions(env); } return result; } MapFieldValue FieldValueInternal::map_value() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); // Make sure this instance is of correct type. if (cached_type_ == Type::kNull) { FIREBASE_ASSERT(env->IsInstanceOf(obj_, util::map::GetClass())); cached_type_ = Type::kMap; } else { FIREBASE_ASSERT(cached_type_ == Type::kMap); } // The following logic is copied from firebase::util::JavaMapToStdMapTemplate, // which we cannot use here directly as it presumes that key and value have // the same type. MapFieldValue result; // Set<Object> key_set = obj_.keySet(); jobject key_set = env->CallObjectMethod(obj_, util::map::GetMethodId(util::map::kKeySet)); CheckAndClearJniExceptions(env); // Iterator iter = key_set.iterator(); jobject iter = env->CallObjectMethod( key_set, util::set::GetMethodId(util::set::kIterator)); CheckAndClearJniExceptions(env); // while (iter.hasNext()) while (env->CallBooleanMethod( iter, util::iterator::GetMethodId(util::iterator::kHasNext))) { CheckAndClearJniExceptions(env); // T key = iter.next(); // T value = obj_.get(key); jobject key_object = env->CallObjectMethod( iter, util::iterator::GetMethodId(util::iterator::kNext)); CheckAndClearJniExceptions(env); std::string key = util::JStringToString(env, key_object); jobject value_object = env->CallObjectMethod( obj_, util::map::GetMethodId(util::map::kGet), key_object); CheckAndClearJniExceptions(env); FieldValue value = FieldValue(new FieldValueInternal(firestore_, value_object)); env->DeleteLocalRef(key_object); env->DeleteLocalRef(value_object); // Once deprecated STLPort support, change back to call emplace. result.insert(std::make_pair(firebase::Move(key), firebase::Move(value))); } env->DeleteLocalRef(iter); env->DeleteLocalRef(key_set); return result; } double FieldValueInternal::double_increment_value() const { // TODO(varconst): implement and test. return {}; } int64_t FieldValueInternal::integer_increment_value() const { // TODO(varconst): implement and test. return {}; } /* static */ FieldValue FieldValueInternal::Delete() { FieldValueInternal* value = new FieldValueInternal(); value->cached_type_ = Type::kDelete; JNIEnv* env = value->firestore_->app()->GetJNIEnv(); value->obj_ = env->NewGlobalRef(delete_); return FieldValue{value}; } /* static */ FieldValue FieldValueInternal::ServerTimestamp() { FieldValueInternal* value = new FieldValueInternal(); value->cached_type_ = Type::kServerTimestamp; JNIEnv* env = value->firestore_->app()->GetJNIEnv(); value->obj_ = env->NewGlobalRef(server_timestamp_); return FieldValue{value}; } /* static */ FieldValue FieldValueInternal::ArrayUnion(std::vector<FieldValue> elements) { FieldValueInternal* value = new FieldValueInternal(); value->cached_type_ = Type::kArrayUnion; JNIEnv* env = value->firestore_->app()->GetJNIEnv(); jobjectArray array = env->NewObjectArray(elements.size(), util::object::GetClass(), nullptr); for (int i = 0; i < elements.size(); ++i) { env->SetObjectArrayElement(array, i, elements[i].internal_->obj_); } jobject obj = env->CallStaticObjectMethod( field_value::GetClass(), field_value::GetMethodId(field_value::kArrayUnion), array); env->DeleteLocalRef(array); CheckAndClearJniExceptions(env); FIREBASE_ASSERT(obj != nullptr); value->obj_ = env->NewGlobalRef(obj); env->DeleteLocalRef(obj); return FieldValue{value}; } /* static */ FieldValue FieldValueInternal::ArrayRemove(std::vector<FieldValue> elements) { FieldValueInternal* value = new FieldValueInternal(); value->cached_type_ = Type::kArrayRemove; JNIEnv* env = value->firestore_->app()->GetJNIEnv(); jobjectArray array = env->NewObjectArray(elements.size(), util::object::GetClass(), nullptr); for (int i = 0; i < elements.size(); ++i) { env->SetObjectArrayElement(array, i, elements[i].internal_->obj_); } jobject obj = env->CallStaticObjectMethod( field_value::GetClass(), field_value::GetMethodId(field_value::kArrayRemove), array); env->DeleteLocalRef(array); CheckAndClearJniExceptions(env); FIREBASE_ASSERT(obj != nullptr); value->obj_ = env->NewGlobalRef(obj); env->DeleteLocalRef(obj); return FieldValue{value}; } /* static */ FieldValue FieldValueInternal::Increment(double) { // TODO(varconst): implement and test. return {}; } /* static */ FieldValue FieldValueInternal::Increment(int64_t) { // TODO(varconst): implement and test. return {}; } /* static */ bool FieldValueInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = field_value::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); // Cache singleton Java objects. jobject obj = env->CallStaticObjectMethod( field_value::GetClass(), field_value::GetMethodId(field_value::kDelete)); FIREBASE_ASSERT(obj != nullptr); delete_ = env->NewGlobalRef(obj); env->DeleteLocalRef(obj); obj = env->CallStaticObjectMethod( field_value::GetClass(), field_value::GetMethodId(field_value::kServerTimestamp)); FIREBASE_ASSERT(obj != nullptr); server_timestamp_ = env->NewGlobalRef(obj); env->DeleteLocalRef(obj); util::CheckAndClearJniExceptions(env); return result; } /* static */ void FieldValueInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); field_value::ReleaseClass(env); util::CheckAndClearJniExceptions(env); // Uncache singleton Java values. env->DeleteGlobalRef(delete_); delete_ = nullptr; env->DeleteGlobalRef(server_timestamp_); server_timestamp_ = nullptr; } bool operator==(const FieldValueInternal& lhs, const FieldValueInternal& rhs) { // Most likely only happens when comparing one with itself or both are Null. if (lhs.obj_ == rhs.obj_) { return true; } // If only one of them is Null, then they cannot equal. if (lhs.obj_ == nullptr || rhs.obj_ == nullptr) { return false; } return lhs.EqualsJavaObject(rhs); } jobject FieldValueInternal::TryGetJobject(const FieldValue& value) { return value.internal_ ? value.internal_->obj_ : nullptr; } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_QUERY_SNAPSHOT_IOS_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_QUERY_SNAPSHOT_IOS_H_ #include <cstddef> #include <vector> #include "firestore/src/include/firebase/firestore/document_change.h" #include "firestore/src/include/firebase/firestore/document_snapshot.h" #include "firestore/src/include/firebase/firestore/metadata_changes.h" #include "firestore/src/include/firebase/firestore/query.h" #include "firestore/src/include/firebase/firestore/query_snapshot.h" #include "firestore/src/include/firebase/firestore/snapshot_metadata.h" #include "firestore/src/ios/firestore_ios.h" #include "absl/types/optional.h" #include "Firestore/core/src/firebase/firestore/api/query_snapshot.h" namespace firebase { namespace firestore { class QuerySnapshotInternal { public: explicit QuerySnapshotInternal(api::QuerySnapshot&& snapshot); FirestoreInternal* firestore_internal(); Query query() const; SnapshotMetadata metadata() const; std::size_t size() const; std::vector<DocumentChange> DocumentChanges( MetadataChanges metadata_changes) const; std::vector<DocumentSnapshot> documents() const; private: api::QuerySnapshot snapshot_; // Cache the results mutable absl::optional<std::vector<DocumentChange>> document_changes_; mutable absl::optional<std::vector<DocumentSnapshot>> documents_; mutable bool changes_include_metadata_ = false; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_QUERY_SNAPSHOT_IOS_H_ <file_sep>// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "remote_config/src/desktop/rest.h" #include <chrono> // NOLINT #include <cstdint> #include <memory> #include <sstream> #include "firebase/app.h" #include "app/instance_id/instance_id_desktop_impl.h" #include "app/meta/move.h" #include "app/rest/request_binary.h" #include "app/rest/response_binary.h" #include "app/rest/transport_builder.h" #include "app/rest/transport_curl.h" #include "app/rest/transport_interface.h" #include "app/rest/util.h" #include "app/src/app_common.h" #include "app/src/log.h" #include "remote_config/src/desktop/config_data.h" #include "remote_config/src/desktop/rest_nanopb_decode.h" #include "remote_config/src/desktop/rest_nanopb_encode.h" // This macro is only used to shorten the enum names, for readability. #define CONFIG_NAMESPACESTATUS(VALUE) \ desktop_config_AppNamespaceConfigTable_NamespaceStatus_##VALUE namespace firebase { namespace remote_config { namespace internal { // The Java library's FirebaseRemoteConfig.java references this file to keep // this value in sync. const int SDK_MAJOR_VERSION = 1; const int SDK_MINOR_VERSION = 3; const int SDK_PATCH_VERSION = 0; const char kTokenScope[] = "*"; RemoteConfigREST::RemoteConfigREST(const firebase::AppOptions& app_options, const LayeredConfigs& configs, uint64_t cache_expiration_in_seconds) : app_package_name_(app_options.package_name()), app_gmp_project_id_(app_options.app_id()), configs_(configs), cache_expiration_in_seconds_(cache_expiration_in_seconds), fetch_future_sem_(0) { rest::util::Initialize(); firebase::rest::InitTransportCurl(); } RemoteConfigREST::~RemoteConfigREST() { firebase::rest::CleanupTransportCurl(); rest::util::Terminate(); } void RemoteConfigREST::Fetch(const App& app) { TryGetInstanceIdAndToken(app); SetupRestRequest(); firebase::rest::CreateTransport()->Perform(rest_request_, &rest_response_); ParseRestResponse(); } void WaitForFuture(const Future<std::string>& future, Semaphore* future_sem, std::string* result, const char* action_name) { // Block and wait until Future is complete. future.OnCompletion( [](const firebase::Future<std::string>& result, void* data) { Semaphore* sem = static_cast<Semaphore*>(data); sem->Post(); }, future_sem); future_sem->Wait(); if (future.status() == firebase::kFutureStatusComplete && future.error() == firebase::instance_id::internal::InstanceIdDesktopImpl::kErrorNone) { *result = *future.result(); } else if (future.status() != firebase::kFutureStatusComplete) { // It is fine if timeout LogWarning("Remote Config Fetch: %s timeout", action_name); } else { // It is fine if failed LogWarning("Remote Config Fetch: Failed to %s. Error %d: %s", action_name, future.error(), future.error_message()); } } void RemoteConfigREST::TryGetInstanceIdAndToken(const App& app) { // Convert the app reference stored in RemoteConfigInternal // pointer for InstanceIdDesktopImpl. App* non_const_app = const_cast<App*>(&app); auto* iid_impl = firebase::instance_id::internal::InstanceIdDesktopImpl::GetInstance( non_const_app); if (iid_impl == nullptr) { // Instance ID not supported. return; } WaitForFuture(iid_impl->GetId(), &fetch_future_sem_, &app_instance_id_, "Get Instance Id"); // Only get token if instance id is retrieved. if (!app_instance_id_.empty()) { WaitForFuture(iid_impl->GetToken(kTokenScope), &fetch_future_sem_, &app_instance_id_token_, "Get Instance Id Token"); } } void RemoteConfigREST::SetupRestRequest() { ConfigFetchRequest config_fetch_request = GetFetchRequestData(); #ifdef DEBUG_SERVER rest_request_.set_verbose(true); #endif // DEBUG_SERVER rest_request_.set_url(kServerURL); rest_request_.set_method(kHTTPMethodPost); rest_request_.add_header(kContentTypeHeaderName, kContentTypeValue); rest_request_.add_header(app_common::kApiClientHeader, App::GetUserAgent()); std::string proto_str = EncodeFetchRequest(config_fetch_request); rest_request_.set_post_fields(proto_str.data(), proto_str.length()); } ConfigFetchRequest RemoteConfigREST::GetFetchRequestData() { ConfigFetchRequest request = ConfigFetchRequest(); GetPackageData(&request.package_data); request.client_version = 2; request.device_type = 5; // DESKTOP #if FIREBASE_PLATFORM_WINDOWS request.device_subtype = 8; // WINDOWS #elif FIREBASE_PLATFORM_OSX request.device_subtype = 9; // OS X #elif FIREBASE_PLATFORM_LINUX request.device_subtype = 10; // LINUX #else #error Unknown operating system. #endif return Move(request); } void RemoteConfigREST::GetPackageData(PackageData* package_data) { package_data->package_name = app_package_name_; package_data->gmp_project_id = app_gmp_project_id_; package_data->namespace_digest = configs_.metadata.digest_by_namespace(); // Check if developer mode enable if (configs_.metadata.GetSetting(kConfigSettingDeveloperMode) == "1") { package_data->custom_variable[kDeveloperModeKey] = "1"; } package_data->app_instance_id = app_instance_id_; package_data->app_instance_id_token = app_instance_id_token_; package_data->requested_cache_expiration_seconds = static_cast<int32_t>(cache_expiration_in_seconds_); if (configs_.fetched.timestamp() == 0) { package_data->fetched_config_age_seconds = -1; } else { package_data->fetched_config_age_seconds = static_cast<int32_t>( (MillisecondsSinceEpoch() - configs_.fetched.timestamp()) / 1000); } package_data->sdk_version = SDK_MAJOR_VERSION * 10000 + SDK_MINOR_VERSION * 100 + SDK_PATCH_VERSION; if (configs_.active.timestamp() == 0) { package_data->active_config_age_seconds = -1; } else { package_data->active_config_age_seconds = static_cast<int32_t>( (MillisecondsSinceEpoch() - configs_.active.timestamp()) / 1000); } } void RemoteConfigREST::ParseRestResponse() { if (rest_response_.status() != kHTTPStatusOk) { FetchFailure(kFetchFailureReasonError); LogError("fetching failure: http code %d", rest_response_.status()); LogDebug("Response body:\n%s", rest_response_.rest::Response::GetBody()); return; } rest_response_.set_use_gunzip(true); const char* data; size_t size; rest_response_.GetBody(&data, &size); std::string body(data, size); if (body == "") { FetchFailure(kFetchFailureReasonError); LogError("fetching failure: empty body"); return; } ParseProtoResponse(body); } void RemoteConfigREST::ParseProtoResponse(const std::string& proto_str) { ConfigFetchResponse response; if (!DecodeResponse(&response, proto_str)) { FetchFailure(kFetchFailureReasonError); LogError("protobuf parsing error"); return; } MetaDigestMap meta_digest; // Start with a copy of the fetched config state. NamespaceKeyValueMap config_map(configs_.fetched.config()); LogDebug("Parsing config response..."); for (auto app_config : response.configs) { LogDebug("Found response config checking app name %s vs %s", app_package_name_.c_str(), app_config.app_name.c_str()); // Check the same app name. if (app_package_name_.compare(app_config.app_name) != 0) continue; LogDebug("Parsing config for app..."); for (auto config : app_config.ns_configs) { switch (config.status) { case CONFIG_NAMESPACESTATUS(NO_CHANGE): meta_digest[config.config_namespace] = config.digest; LogDebug("No change: ns=%s digest=%s", config.config_namespace.c_str(), config.digest.c_str()); break; case CONFIG_NAMESPACESTATUS(UPDATE): meta_digest[config.config_namespace] = config.digest; config_map[config.config_namespace].clear(); for (auto keyvalue : config.key_values) { config_map[config.config_namespace][keyvalue.key] = keyvalue.value; LogDebug("Update: ns=%s kv=(%s, %s)", config.config_namespace.c_str(), keyvalue.key.c_str(), keyvalue.value.c_str()); } break; case CONFIG_NAMESPACESTATUS(NO_TEMPLATE): case CONFIG_NAMESPACESTATUS(NOT_AUTHORIZED): LogDebug("NotAuthorized: ns=%s", config.config_namespace.c_str()); meta_digest.erase(config.config_namespace); config_map.erase(config.config_namespace); break; case CONFIG_NAMESPACESTATUS(EMPTY_CONFIG): LogDebug("EmptyConfig: ns=%s", config.config_namespace.c_str()); meta_digest[config.config_namespace] = config.digest; config_map[config.config_namespace].clear(); break; } } } configs_.metadata.set_digest_by_namespace(meta_digest); configs_.fetched = NamespacedConfigData(config_map, MillisecondsSinceEpoch()); FetchSuccess(kLastFetchStatusSuccess); } void RemoteConfigREST::FetchSuccess(LastFetchStatus status) { ConfigInfo info(configs_.metadata.info()); info.last_fetch_status = status; info.fetch_time = MillisecondsSinceEpoch(); configs_.metadata.set_info(info); } void RemoteConfigREST::FetchFailure(FetchFailureReason reason) { ConfigInfo info(configs_.metadata.info()); info.last_fetch_failure_reason = reason; info.throttled_end_time = MillisecondsSinceEpoch(); info.last_fetch_status = kLastFetchStatusFailure; info.fetch_time = MillisecondsSinceEpoch(); configs_.metadata.set_info(info); } uint64_t RemoteConfigREST::MillisecondsSinceEpoch() { return std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch()) .count(); } } // namespace internal } // namespace remote_config } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_DOCUMENT_REFERENCE_STUB_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_DOCUMENT_REFERENCE_STUB_H_ #include <string> #include "app/src/include/firebase/app.h" #include "firestore/src/common/futures.h" #include "firestore/src/include/firebase/firestore/collection_reference.h" #include "firestore/src/include/firebase/firestore/document_reference.h" #include "firestore/src/stub/firestore_stub.h" namespace firebase { namespace firestore { // This is the stub implementation of DocumentReference. class DocumentReferenceInternal { public: using ApiType = DocumentReference; FirestoreInternal* firestore_internal() { return nullptr; } Firestore* firestore() { return nullptr; } const std::string& id() { return id_; } const std::string& path() { return id_; } CollectionReference Parent() const { return CollectionReference{}; } CollectionReference Collection(const std::string& collection_path) { return CollectionReference{}; } Future<DocumentSnapshot> Get(Source source) const { return FailedFuture<DocumentSnapshot>(); } Future<DocumentSnapshot> GetLastResult() const { return FailedFuture<DocumentSnapshot>(); } Future<void> Set(const MapFieldValue& data, const SetOptions& options) { return FailedFuture<void>(); } Future<void> SetLastResult() const { return FailedFuture<void>(); } Future<void> Update(const MapFieldValue& data) { return FailedFuture<void>(); } Future<void> Update(const MapFieldPathValue& data) { return FailedFuture<void>(); } Future<void> UpdateLastResult() const { return FailedFuture<void>(); } Future<void> Delete() { return FailedFuture<void>(); } Future<void> DeleteLastResult() const { return FailedFuture<void>(); } ListenerRegistration AddSnapshotListener( MetadataChanges metadata_changes, EventListener<DocumentSnapshot>* listener) { return ListenerRegistration{}; } #if defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) ListenerRegistration AddSnapshotListener( MetadataChanges metadata_changes, std::function<void(const DocumentSnapshot&, Error)> callback) { return ListenerRegistration{}; } #endif // defined(FIREBASE_USE_STD_FUNCTION) || defined(DOXYGEN) private: std::string id_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_DOCUMENT_REFERENCE_STUB_H_ <file_sep># Copyright 2019 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # CMake file for the firebase_instance_id library # Common source files used by all platforms set(common_SRCS src/instance_id.cc src/instance_id_internal_base.cc) # Source files used by the Android implementation. set(android_SRCS src/android/instance_id.cc src/android/instance_id_internal.cc) # Source files used by the iOS implementation. set(ios_SRCS src/ios/instance_id.mm src/ios/instance_id_internal.mm) # Source files used by the desktop implementation. set(desktop_SRCS src/desktop/instance_id.cc src/desktop/instance_id_internal.cc) if(ANDROID) set(instance_id_platform_SRCS "${android_SRCS}") elseif(IOS) set(instance_id_platform_SRCS "${ios_SRCS}") else() set(instance_id_platform_SRCS "${desktop_SRCS}") endif() if(ANDROID OR IOS OR use_stub) set(additional_link_LIB) else() set(additional_link_LIB firebase_instance_id_desktop_impl) endif() add_library(firebase_instance_id STATIC ${common_SRCS} ${instance_id_platform_SRCS}) set_property(TARGET firebase_instance_id PROPERTY FOLDER "Firebase Cpp") # Set up the dependency on Firebase App. target_link_libraries(firebase_instance_id PUBLIC firebase_app PRIVATE ${additional_link_LIB} ) # Public headers all refer to each other relative to the src/include directory, # while private headers are relative to the entire C++ SDK directory. target_include_directories(firebase_instance_id PUBLIC ${CMAKE_CURRENT_LIST_DIR}/src/include PRIVATE ${FIREBASE_CPP_SDK_ROOT_DIR} ) target_compile_definitions(firebase_instance_id PRIVATE -DINTERNAL_EXPERIMENTAL=1 ) # Automatically include headers that might not be declared. if(MSVC) add_definitions(/FI"assert.h" /FI"string.h" /FI"stdint.h") else() add_definitions(-include assert.h -include string.h) endif() if(ANDROID) firebase_cpp_proguard_file(instance_id) elseif(IOS) # Enable Automatic Reference Counting (ARC). set_property( TARGET firebase_instance_id APPEND_STRING PROPERTY COMPILE_FLAGS "-fobjc-arc") setup_pod_headers( firebase_instance_id POD_NAMES FirebaseCore FirebaseInstanceID ) endif() if(FIREBASE_CPP_BUILD_TESTS) # Add the tests subdirectory add_subdirectory(tests) endif() cpp_pack_library(firebase_instance_id "") cpp_pack_public_headers() <file_sep>#include "firestore/src/android/document_change_android.h" #include <jni.h> #include "app/src/util_android.h" #include "firestore/src/android/document_change_type_android.h" #include "firestore/src/android/document_snapshot_android.h" #include "firestore/src/android/util_android.h" namespace firebase { namespace firestore { using Type = DocumentChange::Type; // clang-format off #define DOCUMENT_CHANGE_METHODS(X) \ X(Type, "getType", "()Lcom/google/firebase/firestore/DocumentChange$Type;"), \ X(Document, "getDocument", \ "()Lcom/google/firebase/firestore/QueryDocumentSnapshot;"), \ X(OldIndex, "getOldIndex", "()I"), \ X(NewIndex, "getNewIndex", "()I") // clang-format on METHOD_LOOKUP_DECLARATION(document_change, DOCUMENT_CHANGE_METHODS) METHOD_LOOKUP_DEFINITION(document_change, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/DocumentChange", DOCUMENT_CHANGE_METHODS) Type DocumentChangeInternal::type() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject type = env->CallObjectMethod( obj_, document_change::GetMethodId(document_change::kType)); Type result = DocumentChangeTypeInternal::JavaDocumentChangeTypeToDocumentChangeType( env, type); env->DeleteLocalRef(type); CheckAndClearJniExceptions(env); return result; } DocumentSnapshot DocumentChangeInternal::document() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject snapshot = env->CallObjectMethod( obj_, document_change::GetMethodId(document_change::kDocument)); CheckAndClearJniExceptions(env); DocumentSnapshot result{new DocumentSnapshotInternal{firestore_, snapshot}}; env->DeleteLocalRef(snapshot); return result; } std::size_t DocumentChangeInternal::old_index() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jint index = env->CallIntMethod( obj_, document_change::GetMethodId(document_change::kOldIndex)); CheckAndClearJniExceptions(env); return static_cast<std::size_t>(index); } std::size_t DocumentChangeInternal::new_index() const { JNIEnv* env = firestore_->app()->GetJNIEnv(); jint index = env->CallIntMethod( obj_, document_change::GetMethodId(document_change::kNewIndex)); CheckAndClearJniExceptions(env); return static_cast<std::size_t>(index); } /* static */ bool DocumentChangeInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = document_change::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void DocumentChangeInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); document_change::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_FIELD_VALUE_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_FIELD_VALUE_ANDROID_H_ #include <cstdint> #include <string> #include "app/memory/shared_ptr.h" #include "app/src/assert.h" #include "firestore/src/android/wrapper.h" #include "firestore/src/include/firebase/firestore/document_reference.h" #include "firestore/src/include/firebase/firestore/field_value.h" #include "firebase/firestore/geo_point.h" #include "firebase/firestore/timestamp.h" namespace firebase { namespace firestore { class FieldValueInternal : public Wrapper { public: using ApiType = FieldValue; // Wrapper does not allow passing in Java Null object. So we need to deal that // case separately. Generally Java Null is not a valid instance of any // Firestore types except here Null may represent a valid FieldValue of Null // type. FieldValueInternal(FirestoreInternal* firestore, jobject obj); FieldValueInternal(const FieldValueInternal& wrapper); FieldValueInternal(FieldValueInternal&& wrapper); FieldValueInternal(); explicit FieldValueInternal(bool value); explicit FieldValueInternal(int64_t value); explicit FieldValueInternal(double value); explicit FieldValueInternal(Timestamp value); explicit FieldValueInternal(std::string value); FieldValueInternal(const uint8_t* value, size_t size); explicit FieldValueInternal(DocumentReference value); explicit FieldValueInternal(GeoPoint value); explicit FieldValueInternal(std::vector<FieldValue> value); explicit FieldValueInternal(MapFieldValue value); FieldValue::Type type() const; bool boolean_value() const; int64_t integer_value() const; double double_value() const; Timestamp timestamp_value() const; std::string string_value() const; const uint8_t* blob_value() const; size_t blob_size() const; DocumentReference reference_value() const; GeoPoint geo_point_value() const; std::vector<FieldValue> array_value() const; MapFieldValue map_value() const; double double_increment_value() const; int64_t integer_increment_value() const; static FieldValue Delete(); static FieldValue ServerTimestamp(); static FieldValue ArrayUnion(std::vector<FieldValue> elements); static FieldValue ArrayRemove(std::vector<FieldValue> elements); static FieldValue Increment(double d); static FieldValue Increment(int64_t l); private: friend class FirestoreInternal; friend bool operator==(const FieldValueInternal& lhs, const FieldValueInternal& rhs); static bool Initialize(App* app); static void Terminate(App* app); static jobject TryGetJobject(const FieldValue& value); static jobject delete_; static jobject server_timestamp_; // Below are cached type information. It is costly to get type info from // jobject of Object type. So we cache it if we have already known. mutable FieldValue::Type cached_type_ = FieldValue::Type::kNull; mutable SharedPtr<std::vector<uint8_t>> cached_blob_; }; bool operator==(const FieldValueInternal& lhs, const FieldValueInternal& rhs); } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_FIELD_VALUE_ANDROID_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_UNITY_TRANSACTION_FUNCTION_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_UNITY_TRANSACTION_FUNCTION_H_ #include <cstdint> #include <string> #include "app/src/mutex.h" #include "firebase/firestore.h" #include "firebase/firestore/transaction.h" #include "firebase/firestore/firestore_errors.h" namespace firebase { namespace firestore { namespace csharp { // Add this to make this header compile when SWIG is not involved. #ifndef SWIGSTDCALL #if !defined(SWIG) && \ (defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)) #define SWIGSTDCALL __stdcall #else #define SWIGSTDCALL #endif #endif /** * Type of the C# delegate that we will forward transaction Apply() calls to. */ typedef Error(SWIGSTDCALL* UnityTransactionFunctionCallback)( int callback_id, void* transaction, std::string* error_message); /** * A (C++) implementation of TransactionFunction that forwards the calls back * to a C# delegate. */ class UnityTransactionFunction : public TransactionFunction { public: /** * Called by C# to register the global delegate that should receive * transaction callbacks. */ static void SetCallback(UnityTransactionFunctionCallback callback); /** * Called by C# to start a transaction on the provided Firestore instance, * using the specified callback_id to identify it. */ static Future<void> RunTransactionOn(int32_t callback_id, Firestore* firestore); /** * Implementation of TransactionFunction::Apply() that forwards to the C# * global delegate, passing along this->callback_id_ for context. */ Error Apply(Transaction* transaction, std::string* error_message) override; private: explicit UnityTransactionFunction(int32_t callback_id) : callback_id_(callback_id) {} int32_t callback_id_ = -1; static Mutex* mutex_; static UnityTransactionFunctionCallback transaction_function_callback_; }; } // namespace csharp } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_UNITY_TRANSACTION_FUNCTION_H_ <file_sep>#include "firestore/src/android/firebase_firestore_settings_android.h" #include "firestore/src/android/util_android.h" namespace firebase { namespace firestore { // clang-format off #define SETTINGS_BUILDER_METHODS(X) \ X(Constructor, "<init>", "()V", util::kMethodTypeInstance), \ X(SetHost, "setHost", "(Ljava/lang/String;)" \ "Lcom/google/firebase/firestore/FirebaseFirestoreSettings$Builder;"), \ X(SetSslEnabled, "setSslEnabled", "(Z)" \ "Lcom/google/firebase/firestore/FirebaseFirestoreSettings$Builder;"), \ X(SetPersistenceEnabled, "setPersistenceEnabled", "(Z)" \ "Lcom/google/firebase/firestore/FirebaseFirestoreSettings$Builder;"), \ X(SetTimestampsInSnapshotsEnabled, "setTimestampsInSnapshotsEnabled", "(Z)" \ "Lcom/google/firebase/firestore/FirebaseFirestoreSettings$Builder;"), \ X(Build, "build", \ "()Lcom/google/firebase/firestore/FirebaseFirestoreSettings;") // clang-format on METHOD_LOOKUP_DECLARATION(settings_builder, SETTINGS_BUILDER_METHODS) METHOD_LOOKUP_DEFINITION( settings_builder, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/FirebaseFirestoreSettings$Builder", SETTINGS_BUILDER_METHODS) // clang-format off #define SETTINGS_METHODS(X) \ X(GetHost, "getHost", "()Ljava/lang/String;"), \ X(IsSslEnabled, "isSslEnabled", "()Z"), \ X(IsPersistenceEnabled, "isPersistenceEnabled", "()Z") // clang-format on METHOD_LOOKUP_DECLARATION(settings, SETTINGS_METHODS) METHOD_LOOKUP_DEFINITION( settings, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/FirebaseFirestoreSettings", SETTINGS_METHODS) /* static */ jobject FirebaseFirestoreSettingsInternal::SettingToJavaSetting( JNIEnv* env, const Settings& settings) { jobject builder = env->NewObject( settings_builder::GetClass(), settings_builder::GetMethodId(settings_builder::kConstructor)); // Always set Timestamps-in-Snapshots enabled to true. jobject builder_timestamp = env->CallObjectMethod( builder, settings_builder::GetMethodId( settings_builder::kSetTimestampsInSnapshotsEnabled), static_cast<jboolean>(true)); env->DeleteLocalRef(builder); builder = builder_timestamp; // Set host jstring host = env->NewStringUTF(settings.host().c_str()); jobject builder_host = env->CallObjectMethod( builder, settings_builder::GetMethodId(settings_builder::kSetHost), host); env->DeleteLocalRef(builder); env->DeleteLocalRef(host); builder = builder_host; // Set SSL enabled jobject builder_ssl = env->CallObjectMethod( builder, settings_builder::GetMethodId(settings_builder::kSetSslEnabled), static_cast<jboolean>(settings.is_ssl_enabled())); env->DeleteLocalRef(builder); builder = builder_ssl; // Set Persistence enabled jobject builder_persistence = env->CallObjectMethod( builder, settings_builder::GetMethodId(settings_builder::kSetPersistenceEnabled), static_cast<jboolean>(settings.is_persistence_enabled())); env->DeleteLocalRef(builder); builder = builder_persistence; // Build jobject settings_jobj = env->CallObjectMethod( builder, settings_builder::GetMethodId(settings_builder::kBuild)); env->DeleteLocalRef(builder); CheckAndClearJniExceptions(env); return settings_jobj; } /* static */ Settings FirebaseFirestoreSettingsInternal::JavaSettingToSetting(JNIEnv* env, jobject obj) { Settings result; // Set host jstring host = static_cast<jstring>( env->CallObjectMethod(obj, settings::GetMethodId(settings::kGetHost))); result.set_host(util::JStringToString(env, host)); env->DeleteLocalRef(host); // Set SSL enabled jboolean ssl_enabled = env->CallBooleanMethod( obj, settings::GetMethodId(settings::kIsSslEnabled)); result.set_ssl_enabled(ssl_enabled); // Set Persistence enabled jboolean persistence_enabled = env->CallBooleanMethod( obj, settings::GetMethodId(settings::kIsPersistenceEnabled)); result.set_persistence_enabled(persistence_enabled); CheckAndClearJniExceptions(env); return result; } /* static */ bool FirebaseFirestoreSettingsInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = settings_builder::CacheMethodIds(env, activity) && settings::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void FirebaseFirestoreSettingsInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); settings_builder::ReleaseClass(env); settings::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>#include "firestore/src/android/geo_point_android.h" #include <stdint.h> #include "app/src/util_android.h" #include "firestore/src/android/util_android.h" namespace firebase { namespace firestore { // clang-format off #define GEO_POINT_METHODS(X) \ X(Constructor, "<init>", "(DD)V", util::kMethodTypeInstance), \ X(GetLatitude, "getLatitude", "()D"), \ X(GetLongitude, "getLongitude", "()D") // clang-format on METHOD_LOOKUP_DECLARATION(geo_point, GEO_POINT_METHODS) METHOD_LOOKUP_DEFINITION(geo_point, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/GeoPoint", GEO_POINT_METHODS) /* static */ jobject GeoPointInternal::GeoPointToJavaGeoPoint(JNIEnv* env, const GeoPoint& point) { jobject result = env->NewObject( geo_point::GetClass(), geo_point::GetMethodId(geo_point::kConstructor), static_cast<jdouble>(point.latitude()), static_cast<jdouble>(point.longitude())); CheckAndClearJniExceptions(env); return result; } /* static */ GeoPoint GeoPointInternal::JavaGeoPointToGeoPoint(JNIEnv* env, jobject obj) { jdouble latitude = env->CallDoubleMethod( obj, geo_point::GetMethodId(geo_point::kGetLatitude)); jdouble longitude = env->CallDoubleMethod( obj, geo_point::GetMethodId(geo_point::kGetLongitude)); CheckAndClearJniExceptions(env); return GeoPoint{static_cast<double>(latitude), static_cast<double>(longitude)}; } /* static */ jclass GeoPointInternal::GetClass() { return geo_point::GetClass(); } /* static */ bool GeoPointInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = geo_point::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void GeoPointInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); geo_point::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_QUERY_EVENT_LISTENER_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_QUERY_EVENT_LISTENER_H_ #include <cstdint> #include "app/src/callback.h" #include "app/src/mutex.h" #include "firebase/firestore/event_listener.h" #include "firebase/firestore/listener_registration.h" #include "firebase/firestore/metadata_changes.h" #include "firebase/firestore/query_snapshot.h" namespace firebase { namespace firestore { namespace csharp { // Add this to make this header compile when SWIG is not involved. #ifndef SWIGSTDCALL #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__) #define SWIGSTDCALL __stdcall #else #define SWIGSTDCALL #endif #endif // The callbacks that are used by the listener, that need to reach back to C# // callbacks. typedef void(SWIGSTDCALL* QueryEventListenerCallback)(int callback_id, void* snapshot); // Provide a C++ implementation of the EventListener for QuerySnapshot that // can forward the calls back to the C# delegates. class QueryEventListener : public EventListener<QuerySnapshot> { public: QueryEventListener(int32_t callback_id) : callback_id_(callback_id) {} ~QueryEventListener() override {} void OnEvent(const QuerySnapshot& value, Error error) override; static void SetCallback(QueryEventListenerCallback callback); static ListenerRegistration AddListenerTo(int32_t callback_id, Query query, MetadataChanges metadataChanges); private: static void QuerySnapshotEvent(int callback_id, QuerySnapshot value, Error error); int32_t callback_id_; // These static variables are named as global variable instead of private // class member. static Mutex g_mutex; static QueryEventListenerCallback g_query_snapshot_event_listener_callback; }; } // namespace csharp } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_QUERY_EVENT_LISTENER_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_LISTENER_REGISTRATION_IOS_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_LISTENER_REGISTRATION_IOS_H_ #include <memory> #include "firestore/src/ios/firestore_ios.h" #include "Firestore/core/src/firebase/firestore/api/listener_registration.h" namespace firebase { namespace firestore { class ListenerRegistrationInternal { public: ListenerRegistrationInternal( std::unique_ptr<api::ListenerRegistration> registration, FirestoreInternal* firestore); ~ListenerRegistrationInternal(); ListenerRegistrationInternal(const ListenerRegistrationInternal&) = delete; ListenerRegistrationInternal& operator=(const ListenerRegistrationInternal&) = delete; FirestoreInternal* firestore_internal() { return firestore_; } private: friend class FirestoreInternal; void Remove() { registration_->Remove(); } std::unique_ptr<api::ListenerRegistration> registration_; FirestoreInternal* firestore_ = nullptr; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_LISTENER_REGISTRATION_IOS_H_ <file_sep>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "remote_config/src/desktop/rest_nanopb_decode.h" #include "remote_config/src/desktop/rest_nanopb.h" #include "app/meta/move.h" #include "nanopb/pb.h" #include "nanopb/pb_decode.h" namespace firebase { namespace remote_config { namespace internal { NPB_ALIAS_DEF(NpbFetchResponse, desktop_config_ConfigFetchResponse); NPB_ALIAS_DEF(NpbAppConfig, desktop_config_AppConfigTable); NPB_ALIAS_DEF(NpbAppNamespaceConfig, desktop_config_AppNamespaceConfigTable); NPB_ALIAS_DEF(NpbKeyValue, desktop_config_KeyValue); pb_istream_t CreateInputStream(const std::string& source) { return pb_istream_from_buffer( reinterpret_cast<const pb_byte_t*>(source.c_str()), source.size()); } pb_callback_t DecodeStringCB(std::string* destination) { pb_callback_t callback; callback.arg = destination; callback.funcs.decode = [](pb_istream_t* stream, const pb_field_t* field, void** arg) { const char* value = reinterpret_cast<const char*>(stream->state); const size_t size = stream->bytes_left; auto* destination = static_cast<std::string*>(*arg); if (!pb_read(stream, nullptr, size)) { *destination = ""; return false; } *destination = std::string(value, size); return true; }; return callback; } pb_callback_t DecodeKeyValueCB(std::vector<KeyValue>* destination) { pb_callback_t callback; callback.arg = destination; callback.funcs.decode = [](pb_istream_t* stream, const pb_field_t* field, void** arg) { // temporary storage KeyValue key_value; NpbKeyValue npb_key_value = kDefaultNpbKeyValue; npb_key_value.key = DecodeStringCB(&key_value.key); // The `value` in the proto is "bytes", which is compatible with string. npb_key_value.value = DecodeStringCB(&key_value.value); if (!pb_decode(stream, kNpbKeyValueFields, &npb_key_value)) { return false; } auto* destination = static_cast<std::vector<KeyValue>*>(*arg); destination->push_back(Move(key_value)); return true; }; return callback; } pb_callback_t DecodeAppNamespaceConfigCB( std::vector<AppNamespaceConfig>* destination) { pb_callback_t callback; callback.arg = destination; callback.funcs.decode = [](pb_istream_t* stream, const pb_field_t* field, void** arg) { // temporary storage AppNamespaceConfig ns_config; NpbAppNamespaceConfig npb_ns_config = kDefaultNpbAppNamespaceConfig; npb_ns_config.namespace_but_not_a_cpp_reserved_word = DecodeStringCB(&ns_config.config_namespace); npb_ns_config.digest = DecodeStringCB(&ns_config.digest); npb_ns_config.entry = DecodeKeyValueCB(&ns_config.key_values); if (!pb_decode(stream, kNpbAppNamespaceConfigFields, &npb_ns_config)) { return false; } ns_config.status = npb_ns_config.status; auto* destination = static_cast<std::vector<AppNamespaceConfig>*>(*arg); destination->push_back(Move(ns_config)); return true; }; return callback; } pb_callback_t DecodeAppConfigCB(std::vector<AppConfig>* destination) { pb_callback_t callback; callback.arg = destination; callback.funcs.decode = [](pb_istream_t* stream, const pb_field_t* field, void** arg) { AppConfig app_config; NpbAppConfig npb_app_config = kDefaultNpbAppConfig; npb_app_config.app_name = DecodeStringCB(&app_config.app_name); npb_app_config.namespace_config = DecodeAppNamespaceConfigCB(&app_config.ns_configs); if (!pb_decode(stream, kNpbAppConfigFields, &npb_app_config)) { return false; } auto* destination = static_cast<std::vector<AppConfig>*>(*arg); destination->push_back(Move(app_config)); return true; }; return callback; } bool DecodeResponse(ConfigFetchResponse* destination, const std::string& proto_str) { pb_istream_t stream = CreateInputStream(proto_str); ConfigFetchResponse response; NpbFetchResponse npb_response = kDefaultNpbFetchResponse; npb_response.app_config = DecodeAppConfigCB(&response.configs); // Decode the stream triggering the callbacks to capture the data. if (!pb_decode(&stream, kNpbFetchResponseFields, &npb_response)) { return false; } *destination = Move(response); return true; } } // namespace internal } // namespace remote_config } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_TIMESTAMP_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_TIMESTAMP_ANDROID_H_ #include <jni.h> #include "app/src/include/firebase/app.h" #include "firebase/firestore/timestamp.h" namespace firebase { namespace firestore { // This is the non-wrapper Android implementation of Timestamp. Since Timestamp // has most of their method inlined, we use it directly instead of wrapping // around a Java Timestamp object. We still need the helper functions to convert // between the two types. In addition, we also need proper initializer and // terminator for the Java class cache/uncache. class TimestampInternal { public: using ApiType = Timestamp; // Convert a C++ Timestamp into a Java Timestamp. static jobject TimestampToJavaTimestamp(JNIEnv* env, const Timestamp& timestamp); // Convert a Java Timestamp into a C++ Timestamp. static Timestamp JavaTimestampToTimestamp(JNIEnv* env, jobject obj); // Gets the class object of Java Timestamp class. static jclass GetClass(); private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_TIMESTAMP_ANDROID_H_ <file_sep># Toolchain file for building 32-bit Linux libraries set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m32") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32") set(CMAKE_LIBRARY_PATH "/usr/lib/i386-linux-gnu")<file_sep>#include "firestore/src/android/field_path_portable.h" #include <cctype> #include <cstring> #include <sstream> namespace firebase { namespace firestore { namespace { /** * True if the string could be used as a segment in a field path without * escaping. Valid identifies follow the regex [a-zA-Z_][a-zA-Z0-9_]* */ bool IsValidFieldPathSegment(const std::string& segment) { if (segment.empty()) { return false; } auto iter = segment.begin(); if (*iter != '_' && !std::isalpha(*iter)) { return false; } ++iter; while (iter != segment.end()) { if (*iter != '_' && !std::isalnum(*iter)) { return false; } ++iter; } return true; } /** * Escape the segment. The escaping logic comes from Firestore C++ core function * JoinEscaped(). */ std::string Escape(const std::string& segment) { if (IsValidFieldPathSegment(segment)) { return segment; } std::string result; result.reserve(segment.size() * 2 + 2); result.push_back('`'); for (auto iter = segment.begin(); iter != segment.end(); ++iter) { if (*iter == '\\' || *iter == '`') { result.push_back('\\'); } result.push_back(*iter); } result.push_back('`'); return result; } // Returns a vector of strings where each string corresponds to a dot-separated // segment of the given `input`. Any empty segment in `input` will fail // validation, resulting in an assertion firing. Having no dots in `input` is // valid. std::vector<std::string> SplitOnDots(const std::string& input) { auto fail_validation = [&input] { FIREBASE_ASSERT_MESSAGE( false, "Invalid field path (%s). Paths must not be empty, begin with " "'.', end with '.', or contain '..'", input.c_str()); }; // `std::getline()` considers empty input to contain zero segments, and if // input ends with the separator followed by nothing, that is also not // considered a segment. Consequently, these cases are not covered by // validation in the body of the loop below and have to be checked beforehand. if (input.empty() || input[0] == '.' || input[input.size() - 1] == '.') { fail_validation(); } std::vector<std::string> result; std::string current_segment; std::istringstream stream(input); while (std::getline(stream, current_segment, '.')) { if (current_segment.empty()) { fail_validation(); } result.push_back(firebase::Move(current_segment)); } return result; } } // anonymous namespace std::string FieldPathPortable::CanonicalString() const { std::vector<std::string> escaped_segments; escaped_segments.reserve(segments_.size()); std::size_t length = 0; for (const std::string& segment : segments_) { escaped_segments.push_back(Escape(segment)); length += escaped_segments.back().size() + 1; } if (length == 0) { return ""; } std::string result; result.reserve(length); for (const std::string& segment : escaped_segments) { result.append(segment); result.push_back('.'); } result.erase(result.end() - 1); return result; } bool FieldPathPortable::IsKeyFieldPath() const { return size() == 1 && segments_[0] == FieldPathPortable::kDocumentKeyPath; } FieldPathPortable FieldPathPortable::FromDotSeparatedString( const std::string& path) { FIREBASE_ASSERT_MESSAGE( path.find_first_of("~*/[]") == std::string::npos, "Invalid field path (%s). Paths must not contain '~', '*', '/', '[', " "or ']'", path.c_str()); return FieldPathPortable(SplitOnDots(path)); } /* static */ FieldPathPortable FieldPathPortable::FromServerFormat(const std::string& path) { // The following implementation is a STLPort-compatible version of code in // Firestore/core/src/firebase/firestore/model/field_path.cc std::vector<std::string> segments; std::string segment; segment.reserve(path.size()); // Inside backticks, dots are treated literally. bool inside_backticks = false; for (std::size_t i = 0; i < path.size(); ++i) { const char c = path[i]; // std::string (and string_view) may contain embedded nulls. For full // compatibility with Objective C behavior, finish upon encountering the // first terminating null. if (c == '\0') { break; } switch (c) { case '.': if (!inside_backticks) { FIREBASE_ASSERT_MESSAGE( !segment.empty(), "Invalid field path (%s). Paths must not be empty, begin with " "'.', end with '.', or contain '..'", path.c_str()); // Move operation will clear segment, but capacity will remain the // same (not, strictly speaking, required by the standard, but true in // practice). segments.push_back(firebase::Move(segment)); segment.clear(); } else { segment += c; } break; case '`': inside_backticks = !inside_backticks; break; case '\\': FIREBASE_ASSERT_MESSAGE(i + 1 != path.size(), "Trailing escape characters not allowed in %s", path.c_str()); ++i; segment += path[i]; break; default: segment += c; break; } } FIREBASE_ASSERT_MESSAGE( !segment.empty(), "Invalid field path (%s). Paths must not be empty, begin with " "'.', end with '.', or contain '..'", path.c_str()); segments.push_back(firebase::Move(segment)); FIREBASE_ASSERT_MESSAGE(!inside_backticks, "Unterminated ` in path %s", path.c_str()); return FieldPathPortable{firebase::Move(segments)}; } /* static */ FieldPathPortable FieldPathPortable::KeyFieldPath() { return FieldPathPortable{ std::vector<std::string>(1, FieldPathPortable::kDocumentKeyPath)}; } } // namespace firestore } // namespace firebase <file_sep>#include "firestore/src/android/firebase_firestore_exception_android.h" #include <cstring> #include "firestore/src/android/util_android.h" namespace firebase { namespace firestore { // clang-format off #define FIRESTORE_EXCEPTION_METHODS(X) \ X(Constructor, "<init>", \ "(Ljava/lang/String;" \ "Lcom/google/firebase/firestore/FirebaseFirestoreException$Code;)V"), \ X(GetCode, "getCode", \ "()Lcom/google/firebase/firestore/FirebaseFirestoreException$Code;") // clang-format on METHOD_LOOKUP_DECLARATION(firestore_exception, FIRESTORE_EXCEPTION_METHODS) METHOD_LOOKUP_DEFINITION( firestore_exception, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/FirebaseFirestoreException", FIRESTORE_EXCEPTION_METHODS) // clang-format off #define FIRESTORE_EXCEPTION_CODE_METHODS(X) \ X(Value, "value", "()I"), \ X(FromValue, "fromValue", \ "(I)Lcom/google/firebase/firestore/FirebaseFirestoreException$Code;", \ util::kMethodTypeStatic) // clang-format on METHOD_LOOKUP_DECLARATION(firestore_exception_code, FIRESTORE_EXCEPTION_CODE_METHODS) METHOD_LOOKUP_DEFINITION( firestore_exception_code, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/FirebaseFirestoreException$Code", FIRESTORE_EXCEPTION_CODE_METHODS) #define ILLEGAL_STATE_EXCEPTION_METHODS(X) X(Constructor, "<init>", "()V") METHOD_LOOKUP_DECLARATION(illegal_state_exception, ILLEGAL_STATE_EXCEPTION_METHODS) METHOD_LOOKUP_DEFINITION(illegal_state_exception, PROGUARD_KEEP_CLASS "java/lang/IllegalStateException", ILLEGAL_STATE_EXCEPTION_METHODS) /* static */ Error FirebaseFirestoreExceptionInternal::ToErrorCode(JNIEnv* env, jobject exception) { if (exception == nullptr) { return Ok; } // Some of the Precondition failure is thrown as IllegalStateException instead // of a FirebaseFirestoreException. So we convert them into a more meaningful // code. if (env->IsInstanceOf(exception, illegal_state_exception::GetClass())) { return FailedPrecondition; } else if (!IsInstance(env, exception)) { return Unknown; } jobject code = env->CallObjectMethod( exception, firestore_exception::GetMethodId(firestore_exception::kGetCode)); jint code_value = env->CallIntMethod( code, firestore_exception_code::GetMethodId(firestore_exception_code::kValue)); env->DeleteLocalRef(code); CheckAndClearJniExceptions(env); if (code_value > Unauthenticated || code_value < Ok) { return Unknown; } return static_cast<Error>(code_value); } /* static */ std::string FirebaseFirestoreExceptionInternal::ToString(JNIEnv* env, jobject exception) { return util::GetMessageFromException(env, exception); } /* static */ jthrowable FirebaseFirestoreExceptionInternal::ToException( JNIEnv* env, Error code, const char* message) { if (code == Ok) { return nullptr; } // FirebaseFirestoreException requires message to be non-empty. If the caller // does not bother to give details, we assign an arbitrary message here. if (message == nullptr || strlen(message) == 0) { message = "Unknown Exception"; } jstring exception_message = env->NewStringUTF(message); jobject exception_code = env->CallStaticObjectMethod(firestore_exception_code::GetClass(), firestore_exception_code::GetMethodId( firestore_exception_code::kFromValue), static_cast<jint>(code)); jthrowable result = static_cast<jthrowable>(env->NewObject( firestore_exception::GetClass(), firestore_exception::GetMethodId(firestore_exception::kConstructor), exception_message, exception_code)); env->DeleteLocalRef(exception_message); env->DeleteLocalRef(exception_code); CheckAndClearJniExceptions(env); return result; } /* static */ jthrowable FirebaseFirestoreExceptionInternal::ToException( JNIEnv* env, jthrowable exception) { if (IsInstance(env, exception)) { return static_cast<jthrowable>(env->NewLocalRef(exception)); } else { return ToException(env, ToErrorCode(env, exception), ToString(env, exception).c_str()); } } /* static */ bool FirebaseFirestoreExceptionInternal::IsInstance(JNIEnv* env, jobject exception) { return env->IsInstanceOf(exception, firestore_exception::GetClass()); } /* static */ bool FirebaseFirestoreExceptionInternal::IsFirestoreException( JNIEnv* env, jobject exception) { return IsInstance(env, exception) || env->IsInstanceOf(exception, illegal_state_exception::GetClass()); } /* static */ bool FirebaseFirestoreExceptionInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = firestore_exception::CacheMethodIds(env, activity) && firestore_exception_code::CacheMethodIds(env, activity) && illegal_state_exception::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void FirebaseFirestoreExceptionInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); firestore_exception::ReleaseClass(env); firestore_exception_code::ReleaseClass(env); illegal_state_exception::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_FIELD_VALUE_STUB_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_FIELD_VALUE_STUB_H_ #include <cstdint> #include <string> #include "firestore/src/include/firebase/firestore/document_reference.h" #include "firestore/src/include/firebase/firestore/field_value.h" #include "firestore/src/stub/firestore_stub.h" #include "firebase/firestore/geo_point.h" #include "firebase/firestore/timestamp.h" namespace firebase { namespace firestore { // This is the stub implementation of FieldValue. class FieldValueInternal { public: using ApiType = FieldValue; FieldValueInternal() {} explicit FieldValueInternal(bool value) {} explicit FieldValueInternal(int64_t value) {} explicit FieldValueInternal(double value) {} // NOLINTNEXTLINE (performance-unnecessary-value-param) explicit FieldValueInternal(Timestamp value) {} // NOLINTNEXTLINE (performance-unnecessary-value-param) explicit FieldValueInternal(std::string value) {} FieldValueInternal(const uint8_t* value, size_t size) {} // NOLINTNEXTLINE (performance-unnecessary-value-param) explicit FieldValueInternal(DocumentReference value) {} // NOLINTNEXTLINE (performance-unnecessary-value-param) explicit FieldValueInternal(GeoPoint value) {} // NOLINTNEXTLINE (performance-unnecessary-value-param) explicit FieldValueInternal(std::vector<FieldValue> value) {} // NOLINTNEXTLINE (performance-unnecessary-value-param) explicit FieldValueInternal(MapFieldValue value) {} FirestoreInternal* firestore_internal() const { return nullptr; } FieldValue::Type type() const { return FieldValue::Type::kNull; } // The stub implemantion of _value() methods just return default values. We // could FIREBASE_ASSERT(false), since technically the caller shouldn't call // these when the type() is kNull, but for no-op desktop support, it's // probably more helpful to return default values so if the developer is // assuming some schema for their data, it behaves better. bool boolean_value() const { return false; } int64_t integer_value() const { return 0; } double double_value() const { return 0; } Timestamp timestamp_value() const { return Timestamp{}; } std::string string_value() const { return ""; } const uint8_t* blob_value() const { return nullptr; } size_t blob_size() const { return 0; } DocumentReference reference_value() const { return DocumentReference{}; } GeoPoint geo_point_value() const { return GeoPoint{}; } std::vector<FieldValue> array_value() const { return {}; } MapFieldValue map_value() const { return MapFieldValue{}; } double double_increment_value() const { return {}; } std::int64_t integer_increment_value() const { return {}; } static FieldValue Delete() { return FieldValue{}; } static FieldValue ServerTimestamp() { return FieldValue{}; } // NOLINTNEXTLINE (performance-unnecessary-value-param) static FieldValue ArrayUnion(std::vector<FieldValue> elements) { return FieldValue{}; } // NOLINTNEXTLINE (performance-unnecessary-value-param) static FieldValue ArrayRemove(std::vector<FieldValue> elements) { return FieldValue{}; } // NOLINTNEXTLINE (performance-unnecessary-value-param) static FieldValue Increment(double) { return FieldValue{}; } // NOLINTNEXTLINE (performance-unnecessary-value-param) static FieldValue Increment(std::int64_t) { return FieldValue{}; } }; inline bool operator==(const FieldValueInternal& lhs, const FieldValueInternal& rhs) { return false; } } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_FIELD_VALUE_STUB_H_ <file_sep>#include "devtools/build/runtime/get_runfiles_dir.h" #include "app/src/include/firebase/app.h" #include "firestore/src/include/firebase/firestore.h" #include "testing/base/public/gmock.h" #include "gtest/gtest.h" #ifdef _WIN32 #include <windows.h> #else // _WIN32 #include <unistd.h> #endif // _WIN32 // The logic of GetApp() and ProcessEvents() is from // firebase/firestore/client/cpp/testapp/src/desktop/desktop_main.cc. namespace firebase { namespace firestore { App* GetApp(const char* name) { const std::string google_json_dir = devtools_build::testonly::GetTestSrcdir() + "/google3/firebase/firestore/client/cpp/"; App::SetDefaultConfigPath(google_json_dir.c_str()); if (name == nullptr) { return App::Create(); } else { return App::Create(AppOptions{}, name); } } App* GetApp() { return GetApp(nullptr); } // For desktop stub, we just let it sleep for the specified time and return // false, which means the app does not receive an event requesting exit. bool ProcessEvents(int msec) { #ifdef _WIN32 ::Sleep(msec); #else usleep(msec * 1000); #endif // _WIN32 // Simply return false. Reviewers prefer not registering signal and handling // exit request for simplicity. Presumbly, the default signal processing // already deals with the exit correctly and thus we do not need to deal with // it. return false; } FirestoreInternal* CreateTestFirestoreInternal(App* app) { return new FirestoreInternal(app); } void InitializeFirestore(Firestore*) { // No extra initialization necessary } } // namespace firestore } // namespace firebase // MS C++ compiler/linker has a bug on Windows (not on Windows CE), which // causes a link error when _tmain is defined in a static library and UNICODE // is enabled. For this reason instead of _tmain, main function is used on // Windows. See the following link to track the current status of this bug: // http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=394464 // NOLINT #if GTEST_OS_WINDOWS_MOBILE # include <tchar.h> // NOLINT GTEST_API_ int _tmain(int argc, TCHAR** argv) { #else GTEST_API_ int main(int argc, char** argv) { #endif // GTEST_OS_WINDOWS_MOBILE std::cout << "Running main() from gmock_main.cc\n"; // Since Google Mock depends on Google Test, InitGoogleMock() is // also responsible for initializing Google Test. Therefore there's // no need for calling testing::InitGoogleTest() separately. testing::InitGoogleMock(&argc, argv); return RUN_ALL_TESTS(); } <file_sep>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef FIREBASE_INSTANCE_ID_CLIENT_CPP_SRC_DESKTOP_INSTANCE_ID_INTERNAL_H_ #define FIREBASE_INSTANCE_ID_CLIENT_CPP_SRC_DESKTOP_INSTANCE_ID_INTERNAL_H_ #include "app/instance_id/instance_id_desktop_impl.h" #include "app/src/include/firebase/app.h" #include "app/src/safe_reference.h" #include "instance_id/src/instance_id_internal_base.h" namespace firebase { namespace instance_id { namespace internal { class InstanceIdInternal : public InstanceIdInternalBase { public: explicit InstanceIdInternal(App* app); virtual ~InstanceIdInternal(); InstanceIdDesktopImpl* impl() { return impl_; } // Safe reference to this. Set in constructor and cleared in destructor // Should be safe to be copied in any thread because the SharedPtr never // changes, until safe_this_ is completely destroyed. typedef firebase::internal::SafeReference<InstanceIdInternal> InternalRef; typedef firebase::internal::SafeReferenceLock<InstanceIdInternal> InternalRefLock; InternalRef& safe_ref() { return safe_ref_; } public: InstanceIdDesktopImpl* impl_; InternalRef safe_ref_; }; } // namespace internal } // namespace instance_id } // namespace firebase #endif // FIREBASE_INSTANCE_ID_CLIENT_CPP_SRC_DESKTOP_INSTANCE_ID_INTERNAL_H_ <file_sep>#include "firestore/src/ios/field_value_ios.h" #include <utility> #include "firestore/src/include/firebase/firestore/map_field_value.h" #include "firestore/src/ios/converter_ios.h" #include "firestore/src/ios/hard_assert_ios.h" #include "Firestore/core/src/firebase/firestore/nanopb/byte_string.h" namespace firebase { namespace firestore { namespace { using nanopb::ByteString; using Type = FieldValue::Type; } // namespace // Constructors FieldValueInternal::FieldValueInternal(bool value) : type_{Type::kBoolean}, value_{model::FieldValue::FromBoolean(value)} {} FieldValueInternal::FieldValueInternal(int64_t value) : type_{Type::kInteger}, value_{model::FieldValue::FromInteger(value)} {} FieldValueInternal::FieldValueInternal(double value) : type_{Type::kDouble}, value_{model::FieldValue::FromDouble(value)} {} FieldValueInternal::FieldValueInternal(Timestamp value) : type_{Type::kTimestamp}, value_{model::FieldValue::FromTimestamp(value)} {} FieldValueInternal::FieldValueInternal(std::string value) : type_{Type::kString}, value_{model::FieldValue::FromString(std::move(value))} {} FieldValueInternal::FieldValueInternal(const uint8_t* value, size_t size) : type_{Type::kBlob}, value_{model::FieldValue::FromBlob(ByteString{value, size})} {} FieldValueInternal::FieldValueInternal(DocumentReference value) : type_{Type::kReference}, value_{std::move(value)} {} FieldValueInternal::FieldValueInternal(GeoPoint value) : type_{Type::kGeoPoint}, value_{model::FieldValue::FromGeoPoint(value)} {} FieldValueInternal::FieldValueInternal(std::vector<FieldValue> value) : type_{Type::kArray}, value_{std::move(value)} {} FieldValueInternal::FieldValueInternal(MapFieldValue value) : type_{Type::kMap}, value_{std::move(value)} {} // Accessors bool FieldValueInternal::boolean_value() const { HARD_ASSERT_IOS(type_ == Type::kBoolean); return absl::get<model::FieldValue>(value_).boolean_value(); } int64_t FieldValueInternal::integer_value() const { HARD_ASSERT_IOS(type_ == Type::kInteger); return absl::get<model::FieldValue>(value_).integer_value(); } double FieldValueInternal::double_value() const { HARD_ASSERT_IOS(type_ == Type::kDouble); return absl::get<model::FieldValue>(value_).double_value(); } Timestamp FieldValueInternal::timestamp_value() const { HARD_ASSERT_IOS(type_ == Type::kTimestamp); return absl::get<model::FieldValue>(value_).timestamp_value(); } std::string FieldValueInternal::string_value() const { HARD_ASSERT_IOS(type_ == Type::kString); return absl::get<model::FieldValue>(value_).string_value(); } const uint8_t* FieldValueInternal::blob_value() const { HARD_ASSERT_IOS(type_ == Type::kBlob); return absl::get<model::FieldValue>(value_).blob_value().data(); } size_t FieldValueInternal::blob_size() const { HARD_ASSERT_IOS(type_ == Type::kBlob); return absl::get<model::FieldValue>(value_).blob_value().size(); } DocumentReference FieldValueInternal::reference_value() const { HARD_ASSERT_IOS(type_ == Type::kReference); return absl::get<DocumentReference>(value_); } GeoPoint FieldValueInternal::geo_point_value() const { HARD_ASSERT_IOS(type_ == Type::kGeoPoint); return absl::get<model::FieldValue>(value_).geo_point_value(); } std::vector<FieldValue> FieldValueInternal::array_value() const { HARD_ASSERT_IOS(type_ == Type::kArray); return absl::get<ArrayT>(value_); } MapFieldValue FieldValueInternal::map_value() const { HARD_ASSERT_IOS(type_ == Type::kMap); return absl::get<MapT>(value_); } std::vector<FieldValue> FieldValueInternal::array_transform_value() const { HARD_ASSERT_IOS(type_ == Type::kArrayUnion || type_ == Type::kArrayRemove); return absl::get<ArrayT>(value_); } double FieldValueInternal::double_increment_value() const { HARD_ASSERT_IOS(type_ == Type::kIncrementDouble); return absl::get<model::FieldValue>(value_).double_value(); } std::int64_t FieldValueInternal::integer_increment_value() const { HARD_ASSERT_IOS(type_ == Type::kIncrementInteger); return absl::get<model::FieldValue>(value_).integer_value(); } // Creating sentinels FieldValue FieldValueInternal::Delete() { return MakePublic( FieldValueInternal{Type::kDelete, model::FieldValue::Null()}); } FieldValue FieldValueInternal::ServerTimestamp() { return MakePublic( FieldValueInternal{Type::kServerTimestamp, model::FieldValue::Null()}); } FieldValue FieldValueInternal::ArrayUnion(std::vector<FieldValue> elements) { return MakePublic(FieldValueInternal{Type::kArrayUnion, std::move(elements)}); } FieldValue FieldValueInternal::ArrayRemove(std::vector<FieldValue> elements) { return MakePublic( FieldValueInternal{Type::kArrayRemove, std::move(elements)}); } FieldValue FieldValueInternal::Increment(double d) { return MakePublic(FieldValueInternal{Type::kIncrementDouble, model::FieldValue::FromDouble(d)}); } FieldValue FieldValueInternal::Increment(std::int64_t l) { return MakePublic(FieldValueInternal{Type::kIncrementInteger, model::FieldValue::FromInteger(l)}); } // Equality operator bool operator==(const FieldValueInternal& lhs, const FieldValueInternal& rhs) { using ArrayT = FieldValueInternal::ArrayT; using MapT = FieldValueInternal::MapT; auto type = lhs.type(); if (type != rhs.type()) { return false; } switch (type) { case Type::kNull: case Type::kBoolean: case Type::kInteger: case Type::kDouble: case Type::kTimestamp: case Type::kString: case Type::kBlob: case Type::kGeoPoint: // Sentinels case Type::kIncrementDouble: case Type::kIncrementInteger: case Type::kDelete: case Type::kServerTimestamp: return absl::get<model::FieldValue>(lhs.value_) == absl::get<model::FieldValue>(rhs.value_); case Type::kReference: return absl::get<DocumentReference>(lhs.value_) == absl::get<DocumentReference>(rhs.value_); case Type::kArray: case Type::kArrayRemove: case Type::kArrayUnion: return absl::get<ArrayT>(lhs.value_) == absl::get<ArrayT>(rhs.value_); case Type::kMap: return absl::get<MapT>(lhs.value_) == absl::get<MapT>(rhs.value_); } UNREACHABLE(); } std::string Describe(Type type) { switch (type) { // Scalars case Type::kNull: return "FieldValue::Null()"; case Type::kBoolean: return "FieldValue::FromBoolean()"; case Type::kInteger: return "FieldValue::FromInteger()"; case Type::kDouble: return "FieldValue::FromDouble()"; case Type::kTimestamp: return "FieldValue::FromTimestamp()"; case Type::kString: return "FieldValue::FromString()"; case Type::kBlob: return "FieldValue::FromBlob()"; case Type::kReference: return "FieldValue::FromReference()"; case Type::kGeoPoint: return "FieldValue::FromGeoPoint()"; // Containers case Type::kArray: return "FieldValue::FromArray()"; case Type::kMap: return "FieldValue::FromMap()"; // Sentinels case Type::kDelete: return "FieldValue::Delete()"; case Type::kServerTimestamp: return "FieldValue::ServerTimestamp()"; case Type::kArrayUnion: return "FieldValue::ArrayUnion()"; case Type::kArrayRemove: return "FieldValue::ArrayRemove()"; case Type::kIncrementDouble: case Type::kIncrementInteger: return "FieldValue::Increment()"; default: { // TODO(b/147444199): use string formatting. // HARD_FAIL("Unexpected type '%s'", type); auto message = std::string("Unexpected type '") + std::to_string(static_cast<int>(type)) + "'"; HARD_FAIL_IOS(message.c_str()); } } } } // namespace firestore } // namespace firebase <file_sep>// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "instance_id/src/include/firebase/instance_id.h" #include <cstdint> #include <string> #include "instance_id/src/desktop/instance_id_internal.h" #include "instance_id/src/instance_id_internal.h" namespace firebase { namespace instance_id { using internal::InstanceIdInternal; int64_t InstanceId::creation_time() const { return 0; } Future<std::string> InstanceId::GetId() const { if (!instance_id_internal_) return Future<std::string>(); const auto future_handle = instance_id_internal_->FutureAlloc<std::string>( InstanceIdInternal::kApiFunctionGetId); if (instance_id_internal_->impl()) { const auto internal_future = instance_id_internal_->impl()->GetId(); InstanceIdInternal::InternalRef& internal_ref = instance_id_internal_->safe_ref(); internal_future.OnCompletion( [&internal_ref, future_handle](const Future<std::string>& result) { InstanceIdInternal::InternalRefLock lock(&internal_ref); if (lock.GetReference() == nullptr) { return; // deleted. } if (result.error() == 0) { lock.GetReference()->future_api().CompleteWithResult( future_handle, kErrorNone, "", std::string(*result.result())); } else { lock.GetReference()->future_api().Complete( future_handle, kErrorUnknown, result.error_message()); } }); } else { // If there is no InstanceIdDesktopImpl, run as a stub. instance_id_internal_->future_api().CompleteWithResult( future_handle, kErrorNone, "", std::string("FakeId")); } return MakeFuture(&instance_id_internal_->future_api(), future_handle); } Future<void> InstanceId::DeleteId() { if (!instance_id_internal_) return Future<void>(); const auto future_handle = instance_id_internal_->FutureAlloc<void>( InstanceIdInternal::kApiFunctionDeleteId); if (instance_id_internal_->impl()) { const auto internal_future = instance_id_internal_->impl()->DeleteId(); InstanceIdInternal::InternalRef& internal_ref = instance_id_internal_->safe_ref(); internal_future.OnCompletion( [&internal_ref, future_handle](const Future<void>& result) { InstanceIdInternal::InternalRefLock lock(&internal_ref); if (lock.GetReference() == nullptr) { return; // deleted. } if (result.error() == 0) { lock.GetReference()->future_api().Complete(future_handle, kErrorNone, ""); } else { lock.GetReference()->future_api().Complete( future_handle, kErrorUnknown, result.error_message()); } }); } else { // If there is no InstanceIdDesktopImpl, run as a stub. instance_id_internal_->future_api().Complete(future_handle, kErrorNone, ""); } return MakeFuture(&instance_id_internal_->future_api(), future_handle); } Future<std::string> InstanceId::GetToken(const char* entity, const char* scope) { if (!instance_id_internal_) return Future<std::string>(); const auto future_handle = instance_id_internal_->FutureAlloc<std::string>( InstanceIdInternal::kApiFunctionGetToken); if (instance_id_internal_->impl()) { const auto internal_future = instance_id_internal_->impl()->GetToken(scope); InstanceIdInternal::InternalRef& internal_ref = instance_id_internal_->safe_ref(); internal_future.OnCompletion( [&internal_ref, future_handle](const Future<std::string>& result) { InstanceIdInternal::InternalRefLock lock(&internal_ref); if (lock.GetReference() == nullptr) { return; // deleted. } if (result.error() == 0) { lock.GetReference()->future_api().CompleteWithResult( future_handle, kErrorNone, "", std::string(*result.result())); } else { lock.GetReference()->future_api().Complete( future_handle, kErrorUnknown, result.error_message()); } }); } else { // If there is no InstanceIdDesktopImpl, run as a stub. instance_id_internal_->future_api().CompleteWithResult( future_handle, kErrorNone, "", std::string("FakeToken")); } return MakeFuture(&instance_id_internal_->future_api(), future_handle); } Future<void> InstanceId::DeleteToken(const char* entity, const char* scope) { if (!instance_id_internal_) return Future<void>(); const auto future_handle = instance_id_internal_->FutureAlloc<void>( InstanceIdInternal::kApiFunctionDeleteToken); if (instance_id_internal_->impl()) { const auto internal_future = instance_id_internal_->impl()->DeleteToken(scope); InstanceIdInternal::InternalRef& internal_ref = instance_id_internal_->safe_ref(); internal_future.OnCompletion( [&internal_ref, future_handle](const Future<void>& result) { InstanceIdInternal::InternalRefLock lock(&internal_ref); if (lock.GetReference() == nullptr) { return; // deleted. } if (result.error() == 0) { lock.GetReference()->future_api().Complete(future_handle, kErrorNone, ""); } else { lock.GetReference()->future_api().Complete( future_handle, kErrorUnknown, result.error_message()); } }); } else { // If there is no InstanceIdDesktopImpl, run as a stub. instance_id_internal_->future_api().Complete(future_handle, kErrorNone, ""); } return MakeFuture(&instance_id_internal_->future_api(), future_handle); } InstanceId* InstanceId::GetInstanceId(App* app, InitResult* init_result_out) { MutexLock lock(InstanceIdInternal::mutex()); if (init_result_out) *init_result_out = kInitResultSuccess; auto instance_id = InstanceIdInternal::FindInstanceIdByApp(app); if (instance_id) return instance_id; return new InstanceId(app, new InstanceIdInternal(app)); } } // namespace instance_id } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_COMMON_UTIL_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_COMMON_UTIL_H_ #include <string> namespace firebase { namespace firestore { // Returns a reference to an empty string. This is useful for functions that may // need to return the reference while being in a state where they don't have // a string to refer to. const std::string& EmptyString(); } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_COMMON_UTIL_H_ <file_sep>#include "firestore/src/android/source_android.h" namespace firebase { namespace firestore { // clang-format off #define SOURCE_METHODS(X) \ X(Name, "name", "()Ljava/lang/String;") #define SOURCE_FIELDS(X) \ X(Default, "DEFAULT", "Lcom/google/firebase/firestore/Source;", \ util::kFieldTypeStatic), \ X(Server, "SERVER", "Lcom/google/firebase/firestore/Source;", \ util::kFieldTypeStatic), \ X(Cache, "CACHE", "Lcom/google/firebase/firestore/Source;", \ util::kFieldTypeStatic) // clang-format on METHOD_LOOKUP_DECLARATION(source, SOURCE_METHODS, SOURCE_FIELDS) METHOD_LOOKUP_DEFINITION(source, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/Source", SOURCE_METHODS, SOURCE_FIELDS) std::map<Source, jobject>* SourceInternal::cpp_enum_to_java_ = nullptr; /* static */ jobject SourceInternal::ToJavaObject(JNIEnv* env, Source source) { return (*cpp_enum_to_java_)[source]; } /* static */ bool SourceInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = source::CacheMethodIds(env, activity) && source::CacheFieldIds(env, activity); util::CheckAndClearJniExceptions(env); // Cache Java enum values. cpp_enum_to_java_ = new std::map<Source, jobject>(); const auto add_enum = [env](Source source, source::Field field) { jobject value = env->GetStaticObjectField(source::GetClass(), source::GetFieldId(field)); (*cpp_enum_to_java_)[source] = env->NewGlobalRef(value); env->DeleteLocalRef(value); util::CheckAndClearJniExceptions(env); }; add_enum(Source::kDefault, source::kDefault); add_enum(Source::kServer, source::kServer); add_enum(Source::kCache, source::kCache); return result; } /* static */ void SourceInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); source::ReleaseClass(env); util::CheckAndClearJniExceptions(env); // Uncache Java enum values. for (auto& kv : *cpp_enum_to_java_) { env->DeleteGlobalRef(kv.second); } util::CheckAndClearJniExceptions(env); delete cpp_enum_to_java_; cpp_enum_to_java_ = nullptr; } } // namespace firestore } // namespace firebase <file_sep>// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <assert.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include "app/src/app_common.h" #include "app/src/cleanup_notifier.h" #include "app/src/include/firebase/app.h" #include "app/src/include/firebase/internal/platform.h" #include "app/src/log.h" #include "app/src/mutex.h" #include "instance_id/src/include/firebase/instance_id.h" #include "instance_id/src/instance_id_internal.h" // Workaround MSVC's incompatible libc headers. #if FIREBASE_PLATFORM_WINDOWS #define snprintf _snprintf #endif // FIREBASE_PLATFORM_WINDOWS // Module initializer does nothing at the moment. FIREBASE_APP_REGISTER_CALLBACKS(instance_id, { return firebase::kInitResultSuccess; }, {}); namespace firebase { namespace instance_id { namespace internal { std::map<App*, InstanceId*> InstanceIdInternalBase::instance_id_by_app_; // NOLINT Mutex InstanceIdInternalBase::instance_id_by_app_mutex_; // NOLINT InstanceIdInternalBase::InstanceIdInternalBase() : future_api_(kApiFunctionMax) { static const char* kApiIdentifier = "InstanceId"; future_api_id_.reserve(strlen(kApiIdentifier) + 16 /* hex characters in the pointer */ + 1 /* null terminator */); snprintf(&(future_api_id_[0]), future_api_id_.capacity(), "%s0x%016llx", kApiIdentifier, static_cast<unsigned long long>( // NOLINT reinterpret_cast<intptr_t>(this))); } InstanceIdInternalBase::~InstanceIdInternalBase() {} // Associate an InstanceId instance with an app. void InstanceIdInternalBase::RegisterInstanceIdForApp(App* app, InstanceId* instance_id) { MutexLock lock(instance_id_by_app_mutex_); instance_id_by_app_[app] = instance_id; // Cleanup this object if app is destroyed. CleanupNotifier* notifier = CleanupNotifier::FindByOwner(app); assert(notifier); notifier->RegisterObject(instance_id, [](void* object) { InstanceId* instance_id_to_delete = reinterpret_cast<InstanceId*>(object); LogWarning( "InstanceId object 0x%08x should be deleted before the App 0x%08x it " "depends upon.", static_cast<int>(reinterpret_cast<intptr_t>(instance_id_to_delete)), static_cast<int>( reinterpret_cast<intptr_t>(&instance_id_to_delete->app()))); instance_id_to_delete->DeleteInternal(); }); AppCallback::SetEnabledByName("instance_id", true); } // Remove association of InstanceId instance with an App. void InstanceIdInternalBase::UnregisterInstanceIdForApp( App* app, InstanceId* instance_id) { MutexLock lock(instance_id_by_app_mutex_); CleanupNotifier* notifier = CleanupNotifier::FindByOwner(app); assert(notifier); notifier->UnregisterObject(instance_id); auto it = instance_id_by_app_.find(app); if (it == instance_id_by_app_.end()) return; assert(it->second == instance_id); (void)instance_id; instance_id_by_app_.erase(it); } // Find an InstanceId instance associated with an app. InstanceId* InstanceIdInternalBase::FindInstanceIdByApp(App* app) { MutexLock lock(instance_id_by_app_mutex_); auto it = instance_id_by_app_.find(app); return it != instance_id_by_app_.end() ? it->second : nullptr; } } // namespace internal } // namespace instance_id } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_WRITE_BATCH_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_WRITE_BATCH_ANDROID_H_ #include "firestore/src/android/wrapper_future.h" #include "firestore/src/include/firebase/firestore/document_reference.h" #include "firestore/src/include/firebase/firestore/map_field_value.h" #include "firestore/src/include/firebase/firestore/write_batch.h" namespace firebase { namespace firestore { // Each API of WriteBatch that returns a Future needs to define an enum value // here. For example, Foo() and FooLastResult() implementation relies on the // enum value kFoo. The enum values are used to identify and manage Future in // the Firestore Future manager. enum class WriteBatchFn { kCommit = 0, kCount, // Must be the last enum value. }; class WriteBatchInternal : public WrapperFuture<WriteBatchFn, WriteBatchFn::kCount> { public: using ApiType = WriteBatch; using WrapperFuture::WrapperFuture; void Set(const DocumentReference& document, const MapFieldValue& data, const SetOptions& options); void Update(const DocumentReference& document, const MapFieldValue& data); void Update(const DocumentReference& document, const MapFieldPathValue& data); void Delete(const DocumentReference& document); Future<void> Commit(); Future<void> CommitLastResult(); private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_WRITE_BATCH_ANDROID_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_USER_DATA_CONVERTER_IOS_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_USER_DATA_CONVERTER_IOS_H_ #include <utility> #include <vector> #include "firestore/src/include/firebase/firestore/field_path.h" #include "firestore/src/include/firebase/firestore/field_value.h" #include "firestore/src/include/firebase/firestore/map_field_value.h" #include "absl/types/optional.h" #include "Firestore/core/src/firebase/firestore/model/database_id.h" #include "Firestore/core/src/firebase/firestore/model/field_path.h" #include "Firestore/core/src/firebase/firestore/model/field_value.h" namespace firebase { namespace firestore { class SetOptions; namespace core { class ParsedSetData; class ParsedUpdateData; class ParseAccumulator; class ParseContext; } // namespace core class UserDataConverter { public: explicit UserDataConverter(const model::DatabaseId* database_id) : database_id_{database_id} {} /** Parse document data from a non-merge `SetData` call. */ core::ParsedSetData ParseSetData(const MapFieldValue& input) const; /** * Parse document data from `SetData` call. Whether it's treated as a merge is * determined by the given `options`. */ core::ParsedSetData ParseSetData(const MapFieldValue& input, const SetOptions& options) const; /** Parse update data from an `UpdateData` call. */ core::ParsedUpdateData ParseUpdateData(const MapFieldValue& input) const; core::ParsedUpdateData ParseUpdateData(const MapFieldPathValue& input) const; /** * Parse a "query value" (e.g. value in a where filter or a value in a cursor * bound). */ model::FieldValue ParseQueryValue(const FieldValue& input, bool allow_arrays = false) const; private: using UpdateDataInput = std::vector<std::pair<model::FieldPath, const FieldValue*>>; /** Parse document data from a merge `SetData` call. */ core::ParsedSetData ParseMergeData( const MapFieldValue& input, const absl::optional<std::vector<FieldPath>>& field_mask = absl::nullopt) const; /** * Converts a given public C++ `FieldValue` into its internal equivalent. * If the value is a sentinel value, however, returns `nullopt`; the result of * the function in that case will be the side effect of modifying the given * `context`. */ absl::optional<model::FieldValue> ParseData( const FieldValue& input, core::ParseContext&& context) const; model::FieldValue::Array ParseArray(const std::vector<FieldValue>& input, core::ParseContext&& context) const; model::ObjectValue ParseMap(const MapFieldValue& input, core::ParseContext&& context) const; /** * "Parses" the provided sentinel `FieldValue`, adding any necessary * transforms to the field transforms on the given `context`. */ void ParseSentinel(const FieldValue& input, core::ParseContext&& context) const; /** Parses a scalar value (i.e. not a container or a sentinel). */ model::FieldValue ParseScalar(const FieldValue& input, core::ParseContext&& context) const; model::FieldValue::Array ParseArrayTransformElements( const FieldValue& value) const; // Storing `FieldValue`s as pointers in `UpdateDataInput` avoids copying them. // The objects must be valid for the duration of this `ParsedUpdateData` call. core::ParsedUpdateData ParseUpdateData(const UpdateDataInput& input) const; const model::DatabaseId* database_id_ = nullptr; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_USER_DATA_CONVERTER_IOS_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_WRITE_BATCH_STUB_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_WRITE_BATCH_STUB_H_ #include "firestore/src/common/futures.h" #include "firestore/src/include/firebase/firestore/document_reference.h" #include "firestore/src/include/firebase/firestore/map_field_value.h" #include "firestore/src/include/firebase/firestore/write_batch.h" #include "firestore/src/stub/firestore_stub.h" namespace firebase { namespace firestore { // This is the stub implementation of WriteBatch. class WriteBatchInternal { public: using ApiType = WriteBatch; WriteBatchInternal() {} FirestoreInternal* firestore_internal() const { return nullptr; } void Set(const DocumentReference& document, const MapFieldValue& data, const SetOptions& options) {} void Update(const DocumentReference& document, const MapFieldValue& data) {} void Update(const DocumentReference& document, const MapFieldPathValue& data) {} void Delete(const DocumentReference& document) {} Future<void> Commit() { return FailedFuture<void>(); } Future<void> CommitLastResult() const { return FailedFuture<void>(); } }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_WRITE_BATCH_STUB_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_DOCUMENT_CHANGE_STUB_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_DOCUMENT_CHANGE_STUB_H_ #include "firestore/src/include/firebase/firestore/document_change.h" #include "firestore/src/stub/firestore_stub.h" namespace firebase { namespace firestore { // This is the stub implementation of DocumentChange. class DocumentChangeInternal { public: using ApiType = DocumentChange; DocumentChangeInternal() {} FirestoreInternal* firestore_internal() const { return nullptr; } DocumentChange::Type type() const { return DocumentChange::Type::kModified; } DocumentSnapshot document() const { return DocumentSnapshot{}; } std::size_t old_index() const { return 1; } std::size_t new_index() const { return 2; } }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_DOCUMENT_CHANGE_STUB_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_DOCUMENT_CHANGE_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_DOCUMENT_CHANGE_ANDROID_H_ #include <cstdint> #include <string> #include "firestore/src/android/wrapper.h" #include "firestore/src/include/firebase/firestore/document_change.h" namespace firebase { namespace firestore { class DocumentChangeInternal : public Wrapper { public: using ApiType = DocumentChange; using Wrapper::Wrapper; DocumentChange::Type type() const; DocumentSnapshot document() const; std::size_t old_index() const; std::size_t new_index() const; private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_DOCUMENT_CHANGE_ANDROID_H_ <file_sep>#include "firestore/src/include/firebase/firestore/snapshot_metadata.h" #include <ostream> namespace firebase { namespace firestore { std::string SnapshotMetadata::ToString() const { return std::string("SnapshotMetadata{") + "has_pending_writes=" + (has_pending_writes() ? "true" : "false") + ", is_from_cache=" + (is_from_cache() ? "true" : "false") + '}'; } std::ostream& operator<<(std::ostream& out, const SnapshotMetadata& metadata) { return out << metadata.ToString(); } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_EVENT_LISTENER_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_EVENT_LISTENER_ANDROID_H_ #include <jni.h> #include "app/src/embedded_file.h" #include "firestore/src/android/firestore_android.h" #include "firestore/src/include/firebase/firestore/document_snapshot.h" #include "firestore/src/include/firebase/firestore/event_listener.h" namespace firebase { namespace firestore { class EventListenerInternal { public: static void DocumentEventListenerNativeOnEvent(JNIEnv* env, jclass clazz, jlong firestore_ptr, jlong listener_ptr, jobject value, jobject error); static void QueryEventListenerNativeOnEvent(JNIEnv* env, jclass clazz, jlong firestore_ptr, jlong listener_ptr, jobject value, jobject error); static void VoidEventListenerNativeOnEvent(JNIEnv* env, jclass clazz, jlong listener_ptr); static jobject EventListenerToJavaEventListener( JNIEnv* env, FirestoreInternal* firestore, EventListener<DocumentSnapshot>* listener); static jobject EventListenerToJavaEventListener( JNIEnv* env, FirestoreInternal* firestore, EventListener<QuerySnapshot>* listener); static jobject EventListenerToJavaRunnable(JNIEnv* env, EventListener<void>* listener); private: friend class FirestoreInternal; static bool InitializeEmbeddedClasses( App* app, const std::vector<internal::EmbeddedFile>* embedded_files); static void Terminate(App* app); }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_EVENT_LISTENER_ANDROID_H_ <file_sep># Copyright 2018 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # CMake file for the firebase_app library # Define how to generate google_services_resource_(source/header) binary_to_array("google_services_resource" "${CMAKE_CURRENT_LIST_DIR}/google_services.fbs" "firebase::fbs" "${FIREBASE_GEN_FILE_DIR}/app") # Define the resource builds needed for Android firebase_cpp_gradle(":app:app_resources:generateDexJarRelease" "${CMAKE_CURRENT_LIST_DIR}/app_resources/build/dexed.jar") binary_to_array("app_resources" "${CMAKE_CURRENT_LIST_DIR}/app_resources/build/dexed.jar" "firebase_app" "${FIREBASE_GEN_FILE_DIR}/app") firebase_cpp_gradle(":app:google_api_resources:generateDexJarRelease" "${CMAKE_CURRENT_LIST_DIR}/google_api_resources/build/dexed.jar") binary_to_array("google_api_resources" "${CMAKE_CURRENT_LIST_DIR}/google_api_resources/build/dexed.jar" "google_api" "${FIREBASE_GEN_FILE_DIR}/app") firebase_cpp_gradle(":app:invites_resources:generateDexJarRelease" "${CMAKE_CURRENT_LIST_DIR}/invites_resources/build/dexed.jar") binary_to_array("invites_resources" "${CMAKE_CURRENT_LIST_DIR}/invites_resources/build/dexed.jar" "firebase_invites" "${FIREBASE_GEN_FILE_DIR}/app") # Generate build_type_generated.h file(MAKE_DIRECTORY ${FIREBASE_GEN_FILE_DIR}/app/src) set(build_type_header ${FIREBASE_GEN_FILE_DIR}/app/src/build_type_generated.h) add_custom_command( OUTPUT ${build_type_header} COMMAND python "${FIREBASE_SCRIPT_DIR}/build_type_header.py" "--build_type=head" "--output_file=${build_type_header}" COMMENT "Generating build_type_generated header" ) # Generate version.h set(version_header_dir ${FIREBASE_GEN_FILE_DIR}/app/src/include/firebase) set(version_header ${version_header_dir}/version.h) file(MAKE_DIRECTORY ${version_header_dir}) add_custom_command( OUTPUT ${version_header} COMMAND python "${FIREBASE_SCRIPT_DIR}/version_header.py" "--input_file=${FIREBASE_SCRIPT_DIR}/cpp_sdk_version.json" "--output_file=${version_header}" "--build_type=released" COMMENT "Generating version header" ) # Build the google_services_generated.h header from the flatbuffer schema file. set(FLATBUFFERS_FLATC_SCHEMA_EXTRA_ARGS "--no-union-value-namespacing" "--gen-object-api" "--cpp-ptr-type" "flatbuffers::unique_ptr") build_flatbuffers("${CMAKE_CURRENT_LIST_DIR}/google_services.fbs" "" "app_generated_includes" "${FIREBASE_FLATBUFFERS_DEPENDENCIES}" "${FIREBASE_GEN_FILE_DIR}/app" "" "") set(log_common_SRCS src/log.cc src/log.h src/logger.cc src/logger.h) set(log_common_HDRS) set(log_android_SRCS src/jobject_reference.cc src/log_android.cc src/log_android_callback.cc src/util_android.cc) set(log_android_HDRS src/jobject_reference.h src/util_android.h) set(log_ios_SRCS src/log_ios.mm) set(log_ios_HDRS) set(log_desktop_SRCS src/log_stdio.cc) set(log_desktop_HDRS) if(ANDROID) set(log_SRCS "${log_common_SRCS}" "${log_android_SRCS}") set(log_HDRS "${log_common_HDRS}" "${log_android_HDRS}") elseif(IOS) set(log_SRCS "${log_common_SRCS}" "${log_ios_SRCS}") set(log_HDRS "${log_common_HDRS}" "${log_ios_HDRS}") else() set(log_SRCS "${log_common_SRCS}" "${log_desktop_SRCS}") set(log_HDRS "${log_common_HDRS}" "${log_desktop_HDRS}") endif() set(common_SRCS ${google_services_resource_source} ${google_services_resource_header} src/app_common.cc src/app_identifier.cc src/app_options.cc src/callback.cc src/cleanup_notifier.cc src/function_registry.cc src/future.cc src/future_manager.cc src/path.cc src/reference_counted_future_impl.cc src/scheduler.cc src/thread_cpp11.cc src/thread_pthread.cc src/time.cc src/secure/user_secure_manager.cc src/util.cc src/variant.cc src/base64.cc) set(invites_SRCS src/invites/cached_receiver.cc src/invites/invites_receiver_internal.cc) set(app_android_SRCS src/app_android.cc src/google_play_services/availability_android.cc ${app_resources_source} ${google_api_resources_source} ${invites_resources_source} src/invites/android/invites_receiver_internal_android.cc src/invites/android/invites_android_helper.cc src/uuid.cc) set(app_ios_SRCS src/app_ios.mm src/util_ios.mm src/invites/ios/invites_receiver_internal_ios.mm src/invites/ios/invites_ios_startup.mm src/uuid_ios_darwin.mm) set(app_desktop_SRCS src/app_desktop.cc src/invites/stub/invites_receiver_internal_stub.cc src/variant_util.cc) if(ANDROID) set(app_platform_SRCS "${app_android_SRCS}") elseif(IOS) set(app_platform_SRCS "${app_ios_SRCS}") else() if(MSVC) set(app_desktop_extra_SRCS src/secure/user_secure_windows_internal.cc src/locale.cc src/uuid.cc) elseif(APPLE) set(app_desktop_extra_SRCS src/secure/user_secure_darwin_internal.mm src/locale_apple.mm src/uuid_ios_darwin.mm) else() # Linux requires libsecret. pkg_check_modules(LIBSECRET libsecret-1) if(NOT LIBSECRET_FOUND) message(FATAL_ERROR "Unable to find libsecret, which is needed by \ Firebase. It can be installed on supported \ systems via: \ apt-get install libsecret-1-dev") endif() # If building for 32 bit, the include directories might need to be fixed. if("${CMAKE_CXX_FLAGS}" MATCHES "-m32") string(REGEX REPLACE "x86_64" "i386" LIBSECRET_INCLUDE_DIRS "${LIBSECRET_INCLUDE_DIRS}") endif() set(app_desktop_extra_SRCS src/secure/user_secure_linux_internal.cc src/locale.cc src/uuid.cc) endif() set(app_platform_SRCS "${app_desktop_SRCS}" "${app_desktop_extra_SRCS}") endif() set(internal_HDRS src/include/firebase/app.h src/include/firebase/future.h src/include/firebase/internal/common.h src/include/firebase/internal/future_impl.h src/include/firebase/log.h src/include/firebase/util.h src/include/firebase/variant.h src/include/google_play_services/availability.h ${version_header}) set(utility_common_HDRS src/app_common.h src/assert.h ${build_type_header} src/callback.h src/cleanup_notifier.h src/embedded_file.h src/function_registry.h src/future_manager.h src/intrusive_list.h src/log.h src/mutex.h src/optional.h src/path.h src/pthread_condvar.h src/reference_count.h src/reference_counted_future_impl.h src/scheduler.h src/semaphore.h src/thread.h src/time.h src/util.h) set(utility_android_HDRS) set(utility_ios_HDRS) set(utility_desktop_HDRS src/variant_util.h src/invites/cached_receiver.h src/invites/invites_receiver_internal.h src/invites/receiver_interface.h src/invites/sender_receiver_interface.h) if(ANDROID) set(utility_HDRS "${utility_common_HDRS}" "${utility_android_HDRS}") elseif(IOS) set(utility_HDRS "${utility_common_HDRS}" "${utility_ios_HDRS}") else() set(utility_HDRS "${utility_common_HDRS}" "${utility_desktop_HDRS}") endif() set(app_android_HDRS ${app_resources_header} ${google_api_resources_header} ${invites_resources_header} src/invites/android/invites_android_helper.h src/invites/android/invites_receiver_internal_android.h) set(app_ios_HDRS src/invites/ios/invites_receiver_internal_ios.h) set(app_desktop_HDRS src/invites/stub/invites_receiver_internal_stub.h) if(ANDROID) set(app_platform_HDRS "${app_android_HDRS}") elseif(IOS) set(app_platform_HDRS "${app_ios_HDRS}") else() set(app_platform_HDRS "${app_desktop_HDRS}") endif() add_library(firebase_app STATIC ${log_SRCS} ${log_HDRS} ${common_SRCS} ${invites_SRCS} ${app_platform_SRCS} ${internal_HDRS} ${utility_HDRS} ${app_platform_HDRS} ${FIREBASE_GEN_FILE_DIR}/app/google_services_generated.h memory/atomic.h meta/type_traits.h meta/move.h memory/unique_ptr.h memory/shared_ptr.h) set_property(TARGET firebase_app PROPERTY FOLDER "Firebase Cpp") # Disable exceptions in std if (MSVC) target_compile_options(firebase_app PUBLIC /EHs-c-) else() target_compile_options(firebase_app PUBLIC -fno-exceptions) endif() target_include_directories(firebase_app PUBLIC ${CMAKE_CURRENT_LIST_DIR}/src/include ${FIREBASE_GEN_FILE_DIR} PRIVATE ${FIREBASE_CPP_SDK_ROOT_DIR} ${FLATBUFFERS_SOURCE_DIR}/include ${LIBSECRET_INCLUDE_DIRS} ) target_compile_definitions(firebase_app PRIVATE -DINTERNAL_EXPERIMENTAL=1 ) # firebase_app has a dependency on flatbuffers, which needs to be included. target_link_libraries(firebase_app PRIVATE flatbuffers ${LIBSECRET_LIBRARIES} ) # Automatically include headers that might not be declared. if(MSVC) add_definitions(/FI"assert.h" /FI"string.h" /FI"stdint.h") else() add_definitions(-include assert.h -include string.h) endif() # Ensure min/max macros don't get declared on Windows # (so we can use std::min/max) if(MSVC) add_definitions(-DNOMINMAX) endif() if(ANDROID) firebase_cpp_proguard_file(app) elseif(IOS) # Enable Automatic Reference Counting (ARC). set_property( TARGET firebase_app APPEND_STRING PROPERTY COMPILE_FLAGS "-fobjc-arc") # Add empty include path to get root include folder '.' setup_pod_headers( firebase_app POD_NAMES . FirebaseCore FirebaseDynamicLinks FirebaseInstanceID ) endif() if (NOT ANDROID AND NOT IOS) # Add the rest subdirectory, so that other libraries can access it add_subdirectory(rest) add_subdirectory(instance_id) endif() if(FIREBASE_CPP_BUILD_TESTS) # Add the tests subdirectory add_subdirectory(tests) endif() cpp_pack_library(firebase_app "") cpp_pack_public_headers() if (NOT ANDROID AND NOT IOS) cpp_pack_library(flatbuffers "deps/app/external") endif() <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_COLLECTION_REFERENCE_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_COLLECTION_REFERENCE_ANDROID_H_ #include <jni.h> #include "firestore/src/android/firestore_android.h" #include "firestore/src/android/query_android.h" #include "firestore/src/android/wrapper_future.h" namespace firebase { namespace firestore { // To make things simple, CollectionReferenceInternal uses the Future management // from its base class, QueryInternal. Each API of CollectionReference that // returns a Future needs to define an enum value to QueryFn. For example, Foo() // and FooLastResult() implementation relies on the enum value QueryFn::kFoo. // The enum values are used to identify and manage Future in the Firestore // Future manager. using CollectionReferenceFn = QueryFn; // This is the Android implementation of CollectionReference. class CollectionReferenceInternal : public QueryInternal { public: using ApiType = CollectionReference; using QueryInternal::QueryInternal; const std::string& id() const; const std::string& path() const; DocumentReference Parent() const; DocumentReference Document() const; DocumentReference Document(const std::string& document_path) const; Future<DocumentReference> Add(const MapFieldValue& data); Future<DocumentReference> AddLastResult(); private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); // Below are cached call results. mutable std::string cached_id_; mutable std::string cached_path_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_COLLECTION_REFERENCE_ANDROID_H_ <file_sep>#include "firestore/src/ios/firebase_firestore_settings_ios.h" namespace firebase { namespace firestore { api::Settings ToCoreApi(const Settings& from) { api::Settings to; to.set_host(from.host()); to.set_ssl_enabled(from.is_ssl_enabled()); to.set_persistence_enabled(from.is_persistence_enabled()); // TODO(varconst): implement `cache_size_bytes` in public `Settings` and // uncomment. to.set_cache_size_bytes(from.cache_size_bytes()); return to; } } // namespace firestore } // namespace firebase <file_sep>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "database/src/desktop/rest_interface.h" #include <string> #include "app/rest/controller_interface.h" #include "app/rest/request.h" #include "app/rest/response.h" #include "app/rest/transport_builder.h" #include "app/rest/transport_curl.h" #include "app/src/function_registry.h" #include "app/src/include/firebase/app.h" #include "app/src/include/firebase/future.h" #include "app/src/include/firebase/variant.h" #include "app/src/path.h" #include "app/src/reference_counted_future_impl.h" #include "app/src/variant_util.h" #include "database/src/common/query_spec.h" #include "database/src/desktop/data_snapshot_desktop.h" #include "database/src/desktop/database_desktop.h" #include "database/src/include/firebase/database/common.h" #include "database/src/include/firebase/database/listener.h" #include "flatbuffers/stl_emulation.h" namespace firebase { namespace database { namespace internal { const QueryUrlOptions kJustUrlOptions(QueryUrlOptions::kValueUrl, QueryUrlOptions::kNoToken, nullptr); const QueryUrlOptions kAuthorizedUrlOptions(QueryUrlOptions::kValueUrl, QueryUrlOptions::kIncludeAuthToken, nullptr); const QueryUrlOptions kAuthorizedPriorityUrlOptions( QueryUrlOptions::kPriorityUrl, QueryUrlOptions::kIncludeAuthToken, nullptr); static Error ParseErrorString(const char* error_string) { const char kErrorStringPermissionDenied[] = "Permission denied"; if (strcmp(error_string, kErrorStringPermissionDenied) == 0) { return kErrorPermissionDenied; } else { // TODO(amablue): What other error string can we get here? return kErrorUnknownError; } } class DatabaseRequest : public rest::Request { public: DatabaseRequest(DatabaseInternal* database) { // NOTE: We're not sending the x-goog-api-client user agent header returned // by App::GetUserAgent() to avoid bloating each request. add_header("User-Agent", database->host_info().user_agent().c_str()); } }; void SseResponse::MarkCompleted() { rest::Response::MarkCompleted(); Finalize(); } void SseResponse::MarkCanceled() { rest::Response::MarkCanceled(); Finalize(); } void SseResponse::Finalize() { semaphore_.Post(); } void SseResponse::WaitForCompletion() { // This is here purely to block until the mutex is released. semaphore_.Wait(); } ParseStatus ParseResponse(const std::string& body, Path* out_relative_path, Variant* out_diff, bool* is_overwrite, Error* out_error, std::string* out_error_string) { // Responses take the following form (everything between the ---) // // --- // event: <Event Name> // data: {"path":<Path>,"data":<JSON Data>} // --- // // For more information, see: // https://firebase.google.com/docs/reference/rest/database/#section-streaming const std::string kEventPrefix = "event: "; const std::string kDataPrefix = "data: "; std::istringstream input(body); std::string line; // Get the method. std::getline(input, line); if (!StringStartsWith(line, kEventPrefix)) { // If we didn't get a segment starting with "event: " then this is an error // string. *out_error = ParseErrorString(line.c_str()); *out_error_string = line; return kParseError; } std::string method(line, kEventPrefix.size()); // put, patch, keep-alive, cancel and auth_revoked are the only values the // server will send down. // https://firebase.google.com/docs/reference/rest/database/#section-streaming if (method != "put" && method != "patch") { if (method == "keep-alive") { *out_error = kErrorNone; return kParseKeepAlive; } else if (method == "cancel") { *out_error = kErrorPermissionDenied; return kParseError; } else if (method == "auth_revoked") { *out_error = kErrorPermissionDenied; return kParseError; } else { logger_->LogError("Unexpected method (%s).", method.c_str()); // If we've errored at this point something has gone wrong on the server // and it sent us bad data. *out_error = kErrorUnknownError; return kParseError; } } // Get the JSON string. std::getline(input, line); if (!StringStartsWith(line, kDataPrefix)) { logger_->LogError("Malformed data sent to client: Expected %s, got %s.", kDataPrefix.c_str(), line.c_str()); // If we've errored at this point something has gone wrong on the server and // it sent us bad data. *out_error = kErrorUnknownError; return kParseError; } std::string json(line.begin() + kDataPrefix.size(), line.end()); // Now that we have the JSON string, convert it into a variant. This variant // should be a map that consists of two fields: "path", which is a string, and // "data", which is the data to be placed at the location given by "path". Variant json_data = util::JsonToVariant(json.c_str()); if (!json_data.is_map()) { logger_->LogError("Malformed JSON sent to client: Expected object, got %s.", Variant::TypeName(json_data.type())); // If we've errored at this point something has gone wrong on the server and // it sent us bad data. *out_error = kErrorUnknownError; return kParseError; } // Get the path from the variant. auto path_iter = json_data.map().find(Variant("path")); if (path_iter == json_data.map().end() || !path_iter->second.is_string()) { logger_->LogError( "Malformed JSON sent to client: Expected \"path\" field."); // If we've errored at this point something has gone wrong on the server and // it sent us bad data. *out_error = kErrorUnknownError; return kParseError; } Path path(path_iter->second.mutable_string()); // Get the data from the variant. auto data_iter = json_data.map().find(Variant("data")); if (data_iter == json_data.map().end()) { logger_->LogError( "Malformed JSON sent to client: Expected \"data\" field."); // If we've errored at this point something has gone wrong on the server and // it sent us bad data. *out_error = kErrorUnknownError; return kParseError; } Variant& incoming_data = data_iter->second; *out_relative_path = path; *out_diff = incoming_data; *is_overwrite = (method == "put"); *out_error = kErrorNone; return kParseSuccess; } QueryResponse::~QueryResponse() { database_->UnregisterQueryResponse(query_spec_, value_listener_, child_listener_); } bool QueryResponse::ProcessBody(const char* buffer, size_t length) { MutexLock lock(mutex_); if (value_listener_ == nullptr && child_listener_ == nullptr) { // Listener has been unregistered already. return false; } std::string body(buffer, length); Path relative_path; Variant diff; bool is_overwrite; switch (ParseResponse(body, &relative_path, &diff, &is_overwrite, &error_, &error_string_)) { case kParseSuccess: { Path full_path = query_spec_.path.GetChild(relative_path); if (is_overwrite) { database_->ApplyServerOverwrite(full_path, diff); } else { database_->ApplyServerMerge(full_path, diff); } return true; } case kParseKeepAlive: { return true; } case kParseError: { // After an error has been detected the response MarkComplete will be // called automatically. return false; } } } void QueryResponse::ClearListener() { MutexLock lock(mutex_); value_listener_ = nullptr; child_listener_ = nullptr; } void QueryResponse::MarkCompleted() { SseResponse::MarkCompleted(); } void QueryResponse::MarkCanceled() { error_ = kErrorWriteCanceled; SseResponse::MarkCanceled(); } void QueryResponse::Finalize() { MutexLock lock(mutex_); const char* effective_error_string = error_string_.empty() ? GetErrorMessage(error_) : error_string_.c_str(); // Only one will be nonnull. if (value_listener_) value_listener_->OnCancelled(error_, effective_error_string); if (child_listener_) child_listener_->OnCancelled(error_, effective_error_string); SseResponse::Finalize(); } SetValueResponse::SetValueResponse(DatabaseInternal* database, const Path& path, SafeFutureHandle<void> handle, ReferenceCountedFutureImpl* ref_future, WriteId write_id) : database_(database), path_(path), handle_(handle), ref_future_(ref_future), write_id_(write_id), error_(kErrorNone), error_string_() {} bool SetValueResponse::ProcessBody(const char* buffer, size_t length) { std::string body(buffer, length); // The response takes the form of a JSON string. If the response contains // the field "error" then something has gone wrong. Revert the change and // report the error. Variant json_data = util::JsonToVariant(body.c_str()); if (json_data.is_map()) { auto iter = json_data.map().find("error"); if (iter != json_data.map().end()) { const Variant& error_variant = iter->second; if (error_variant.is_string()) { error_string_ = error_variant.string_value(); error_ = ParseErrorString(error_string_.c_str()); } else { // If our error wasn't a string variant something very weird happened. error_ = kErrorUnknownError; } } } return rest::Response::ProcessBody(buffer, length); } void SetValueResponse::MarkCompleted() { rest::Response::MarkCompleted(); switch (status()) { case rest::util::HttpSuccess: { // 200 // No error. break; } case rest::util::HttpBadRequest: { // 400 error_ = kErrorOperationFailed; break; } case rest::util::HttpUnauthorized: { // 401 error_ = kErrorPermissionDenied; break; } case 503: { // Service unavailable. error_ = kErrorUnavailable; break; } default: { error_ = kErrorUnknownError; break; } } // If there was an error, revert the change locally. if (error_ != kErrorNone) { database_->RevertWriteId(path_, write_id_); } // Complete the future. const char* effective_error_string = error_string_.empty() ? GetErrorMessage(error_) : error_string_.c_str(); ref_future_->Complete(handle_, error_, effective_error_string); } void SetValueResponse::MarkCanceled() { rest::Response::MarkCompleted(); // If the operation was canceled, revert the change and complete the future. database_->RevertWriteId(path_, write_id_); ref_future_->Complete(handle_, kErrorWriteCanceled); } SingleValueListener::SingleValueListener(DatabaseInternal* database, ReferenceCountedFutureImpl* future, SafeFutureHandle<DataSnapshot> handle) : database_(database), future_(future), handle_(handle) {} SingleValueListener::~SingleValueListener() {} void SingleValueListener::OnValueChanged(const DataSnapshot& snapshot) { database_->RemoveSingleValueListener(this); future_->CompleteWithResult<DataSnapshot>(handle_, kErrorNone, "", snapshot); delete this; } void SingleValueListener::OnCancelled(const Error& error_code, const char* error_message) { database_->RemoveSingleValueListener(this); future_->Complete(handle_, error_code, error_message); delete this; } void GetValueResponse::MarkCompleted() { rest::Response::MarkCompleted(); const char* body = GetBody(); if (!body) { // No body received - return error. future_->CompleteWithResult<DataSnapshot>( handle_, kErrorUnknownError, DataSnapshotInternal::GetInvalidDataSnapshot()); } if (*single_value_listener_holder_) { // TODO(b/68864049): Check status() for error code. DataSnapshot snapshot( new DataSnapshotInternal(database_, path_, util::JsonToVariant(body))); (*single_value_listener_holder_)->OnValueChanged(snapshot); } } void RestCall(DatabaseInternal* database, const std::string& url, const char* method, const std::string& post_fields, rest::Response* response) { struct RestCallArgs { DatabaseInternal* database; std::string url; const char* method; std::string post_fields; rest::Response* response; }; auto* args = new RestCallArgs(); args->database = database; args->url = url; args->method = method; args->post_fields = post_fields; args->response = response; Thread( [](void* userdata) { auto* args = static_cast<RestCallArgs*>(userdata); auto transport = firebase::rest::CreateTransport(); DatabaseRequest request(args->database); request.set_url(args->url.c_str()); request.set_method(args->method); request.set_post_fields(args->post_fields.c_str()); transport->Perform(request, args->response); delete args->response; delete args; }, args) .Detach(); } void SseRestCall(DatabaseInternal* database, const QuerySpec& query_spec, const char* url, SseResponse* response, flatbuffers::unique_ptr<rest::Controller>* controller_out) { struct SseRestCallArgs { SseRestCallArgs(DatabaseInternal* database_, const QuerySpec& query_spec_, rest::TransportCurl* transport_) : database(database_), query_spec(query_spec_), transport(transport_), request(database_), response(nullptr) {} DatabaseInternal* database; QuerySpec query_spec; rest::TransportCurl* transport; DatabaseRequest request; SseResponse* response; }; auto* args = new SseRestCallArgs(database, query_spec, new rest::TransportCurl()); args->transport->set_is_async(true); args->request.set_url(url); args->request.set_method("GET"); args->request.add_header("Accept", "text/event-stream"); args->response = response; args->transport->Perform(args->request, args->response, controller_out); Thread( [](void* userdata) { auto* args = static_cast<SseRestCallArgs*>(userdata); args->response->WaitForCompletion(); delete args->transport; delete args->response; delete args; }, args) .Detach(); } static const char* ArgumentSeparator(bool* first) { const char* result = *first ? "?" : "&"; if (*first) *first = false; return result; } // Returns the auth token for the current user, if there is a current user, // and they have a token, and auth exists as part of the app. // Otherwise, returns an empty string. static std::string GetAuthToken(DatabaseInternal* database) { std::string result; App* app = database->GetApp(); if (app) { app->function_registry()->CallFunction( ::firebase::internal::FnAuthGetCurrentToken, app, nullptr, &result); } return result; } std::string GetUrlWithQuery(const QueryUrlOptions& options, DatabaseInternal* database, const QuerySpec& query_spec) { bool first = true; std::string url; url += database->database_url(); url += "/"; url += query_spec.path.str(); if (options.url_type == QueryUrlOptions::kPriorityUrl) { url += "/.priority.json"; } else { url += ".json"; } if (options.url_type == QueryUrlOptions::kValuePriorityUrl) { url += ArgumentSeparator(&first); url += "format=export"; } if (options.use_auth_token == QueryUrlOptions::kIncludeAuthToken) { // Grab the current user's auth token, if any. std::string credential = GetAuthToken(database); if (!credential.empty()) { url += ArgumentSeparator(&first); url += "auth="; url += rest::util::EncodeUrl(credential); } } if (options.query_spec) { switch (options.query_spec->params.order_by) { case QueryParams::kOrderByPriority: { url += ArgumentSeparator(&first); url += "orderBy=\"$priority\""; break; } case QueryParams::kOrderByChild: { url += ArgumentSeparator(&first); url += "orderBy=\""; url += rest::util::EncodeUrl(options.query_spec->params.order_by_child); url += "\""; break; } case QueryParams::kOrderByKey: { url += ArgumentSeparator(&first); url += "orderBy=\"$key\""; break; } case QueryParams::kOrderByValue: { url += ArgumentSeparator(&first); url += "orderBy=\"$value\""; break; } } if (!options.query_spec->params.start_at_value.is_null()) { url += ArgumentSeparator(&first); url += "startAt="; url += rest::util::EncodeUrl( util::VariantToJson(options.query_spec->params.start_at_value)); } else if (!options.query_spec->params.start_at_child_key.empty()) { url += ArgumentSeparator(&first); url += "startAt="; url += rest::util::EncodeUrl(options.query_spec->params.start_at_child_key); } if (!options.query_spec->params.end_at_value.is_null()) { url += ArgumentSeparator(&first); url += "endAt="; url += rest::util::EncodeUrl( util::VariantToJson(options.query_spec->params.end_at_value)); } else if (!options.query_spec->params.end_at_child_key.empty()) { url += ArgumentSeparator(&first); url += "endAt="; url += rest::util::EncodeUrl(options.query_spec->params.end_at_child_key); } if (!options.query_spec->params.equal_to_value.is_null()) { url += ArgumentSeparator(&first); url += "equalTo="; url += rest::util::EncodeUrl( util::VariantToJson(options.query_spec->params.equal_to_value)); } else if (!options.query_spec->params.equal_to_child_key.empty()) { url += ArgumentSeparator(&first); url += "equalTo="; url += rest::util::EncodeUrl(options.query_spec->params.equal_to_child_key); } if (options.query_spec->params.limit_first != 0) { url += ArgumentSeparator(&first); url += "limitToFirst="; url += std::to_string(options.query_spec->params.limit_first); } if (options.query_spec->params.limit_last != 0) { url += ArgumentSeparator(&first); url += "limitToLast="; url += std::to_string(options.query_spec->params.limit_last); } } return url; } } // namespace internal } // namespace database } // namespace firebase <file_sep>#include "firebase/csharp/query_event_listener.h" #include "app/src/assert.h" #include "firebase/firestore/query.h" namespace firebase { namespace firestore { namespace csharp { ::firebase::Mutex QueryEventListener::g_mutex; QueryEventListenerCallback QueryEventListener::g_query_snapshot_event_listener_callback = nullptr; void QueryEventListener::OnEvent(const QuerySnapshot& value, Error error) { MutexLock lock(g_mutex); if (g_query_snapshot_event_listener_callback) { firebase::callback::AddCallback(firebase::callback::NewCallback( QuerySnapshotEvent, callback_id_, value, error)); } } /* static */ void QueryEventListener::SetCallback(QueryEventListenerCallback callback) { MutexLock lock(g_mutex); if (!callback) { g_query_snapshot_event_listener_callback = nullptr; return; } if (g_query_snapshot_event_listener_callback) { FIREBASE_ASSERT(g_query_snapshot_event_listener_callback == callback); } else { g_query_snapshot_event_listener_callback = callback; } } /* static */ ListenerRegistration QueryEventListener::AddListenerTo( int32_t callback_id, Query query, MetadataChanges metadata_changes) { QueryEventListener listener(callback_id); // TODO(zxu): For now, we call the one with lambda instead of EventListener // pointer so we do not have to manage the ownership of the listener. We // might want to extend the design to manage listeners and call the one with // EventListener parameter e.g. adding extra parameter in the API to specify // whether ownership is transferred. return query.AddSnapshotListener( metadata_changes, [listener](const QuerySnapshot& value, Error error) mutable { listener.OnEvent(value, error); }); } /* static */ void QueryEventListener::QuerySnapshotEvent(int callback_id, QuerySnapshot value, Error error) { MutexLock lock(g_mutex); if (error != Ok || g_query_snapshot_event_listener_callback == nullptr) { return; } // The ownership is passed through the call to C# handler. QuerySnapshot* copy = new QuerySnapshot(value); g_query_snapshot_event_listener_callback(callback_id, copy); } } // namespace csharp } // namespace firestore } // namespace firebase <file_sep>#include "firestore/src/ios/credentials_provider_ios.h" #include <utility> #include "firestore/src/ios/hard_assert_ios.h" #include "firebase/firestore/firestore_errors.h" #include "Firestore/core/src/firebase/firestore/util/status.h" namespace firebase { namespace firestore { namespace { using auth::CredentialChangeListener; using auth::Token; using auth::TokenListener; using auth::User; using ::firebase::auth::Auth; using util::Status; using util::StatusOr; User GetCurrentUser(Auth* firebase_auth) { ::firebase::auth::User* user = firebase_auth->current_user(); if (user != nullptr) { return User(user->uid()); } return User(); } StatusOr<Token> ConvertToken(const Future<std::string>& future, Auth* firebase_auth) { if (future.error() != Error::Ok) { return Status(static_cast<Error>(future.error()), future.error_message()); } return Token(*future.result(), GetCurrentUser(firebase_auth)); } // Converts the result of the given future into an `firestore::auth::Token` // and invokes the `listener` with the token. If the future is failed, invokes // the `listener` with the error. If the current token generation is higher // than `expected_generation`, will invoke the `listener` with "aborted" // error. `future_token` must be a completed future. void OnToken(const Future<std::string>& future_token, Auth* firebase_auth, int token_generation, const TokenListener& listener, int expected_generation) { HARD_ASSERT_IOS(future_token.status() == FutureStatus::kFutureStatusComplete, "Expected to receive a completed future"); if (expected_generation != token_generation) { // Cancel the request since the user may have changed while the request was // outstanding, so the response is likely for a previous user (which user, // we can't be sure). listener(Status(Error::Aborted, "GetToken() aborted due to token change.")); return; } listener(ConvertToken(future_token, firebase_auth)); } } // namespace FirebaseCppCredentialsProvider::FirebaseCppCredentialsProvider( Auth* firebase_auth) : contents_(std::make_shared<Contents>(NOT_NULL(firebase_auth))) { } void FirebaseCppCredentialsProvider::SetCredentialChangeListener( CredentialChangeListener listener) { std::lock_guard<std::recursive_mutex> lock(contents_->mutex); if (!listener) { HARD_ASSERT_IOS(change_listener_, "Change listener removed without being set!"); change_listener_ = {}; // Note: not removing the Auth listener here because the Auth might already // be destroyed. Note that Auth listeners unregister themselves upon // destruction anyway. return; } HARD_ASSERT_IOS(!change_listener_, "Set change listener twice!"); change_listener_ = std::move(listener); change_listener_(GetCurrentUser(contents_->firebase_auth)); // Note: make sure to only register the Auth listener _after_ calling // `Auth::current_user` for the first time. The reason is that upon the only // first call only, `Auth::current_user` might block as it would // asynchronously notify Auth listeners; getting the Firestore listener // notified while `Auth::current_user` is pending can lead to a deadlock. contents_->firebase_auth->AddAuthStateListener(this); } void FirebaseCppCredentialsProvider::GetToken(TokenListener listener) { std::lock_guard<std::recursive_mutex> lock(contents_->mutex); if (IsSignedIn()) { RequestToken(std::move(listener)); } else { listener(Token::Unauthenticated()); } } void FirebaseCppCredentialsProvider::InvalidateToken() { std::lock_guard<std::recursive_mutex> lock(contents_->mutex); force_refresh_token_ = true; } void FirebaseCppCredentialsProvider::OnAuthStateChanged(Auth* firebase_auth) { std::lock_guard<std::recursive_mutex> lock(contents_->mutex); // The currently signed-in user may have changed, increase the token // generation to reflect that. ++(contents_->token_generation); if (change_listener_) { change_listener_(GetCurrentUser(contents_->firebase_auth)); } } // Private member functions void FirebaseCppCredentialsProvider::RequestToken(TokenListener listener) { HARD_ASSERT_IOS(IsSignedIn(), "Cannot get token when there is no signed-in user"); bool force_refresh = force_refresh_token_; force_refresh_token_ = false; // Take note of the current value of `token_generation` so that this request // can fail if there is a token change while the request is outstanding. int expected_generation = contents_->token_generation; auto future = contents_->firebase_auth->current_user()->GetToken(force_refresh); std::weak_ptr<Contents> weak_contents(contents_); // Note: if the future happens to be already completed (either because the // token was readily available, or theoretically because the Auth token // request finished so quickly), this completion will be invoked // synchronously. Because the mutex is recursive, it's okay to lock it again // in that case. future.OnCompletion( // TODO(c++14): move `listener` into the lambda. [listener, expected_generation, weak_contents](const Future<std::string>& future_token) { auto contents = weak_contents.lock(); // Auth may invoke the callback when credentials provider has already // been destroyed. if (!contents) { return; } std::lock_guard<std::recursive_mutex> lock(contents->mutex); OnToken(future_token, contents->firebase_auth, contents->token_generation, std::move(listener), expected_generation); }); } bool FirebaseCppCredentialsProvider::IsSignedIn() const { return contents_->firebase_auth->current_user() != nullptr; } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_UTIL_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_UTIL_ANDROID_H_ #include <jni.h> #include <string> #include "app/src/util_android.h" #if __cpp_exceptions #include <exception> #endif // __cpp_exceptions namespace firebase { namespace firestore { // By default, google3 disables exception and so does in the release. We enable // exception only in the test build to test the abort cases. DO NOT enable // exception for non-test build, which is against the style guide. #if __cpp_exceptions class FirestoreException : public std::exception { public: explicit FirestoreException(const std::string& message) : message_(message) {} const char* what() const noexcept override { return message_.c_str(); } private: std::string message_; }; inline bool CheckAndClearJniExceptions(JNIEnv* env) { jobject java_exception = env->ExceptionOccurred(); if (java_exception == nullptr) { return false; } util::CheckAndClearJniExceptions(env); FirestoreException cc_exception{ util::GetMessageFromException(env, java_exception)}; env->DeleteLocalRef(java_exception); throw cc_exception; } #else // __cpp_exceptions inline bool CheckAndClearJniExceptions(JNIEnv* env) { return util::CheckAndClearJniExceptions(env); } #endif // __cpp_exceptions } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_UTIL_ANDROID_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_QUERY_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_QUERY_ANDROID_H_ #include <jni.h> #include <cstdint> #include "app/src/reference_counted_future_impl.h" #include "app/src/util_android.h" #include "firestore/src/android/wrapper_future.h" #include "firestore/src/include/firebase/firestore/field_path.h" #include "firestore/src/include/firebase/firestore/query.h" namespace firebase { namespace firestore { class Firestore; // Each API of Query that returns a Future needs to define an enum value here. // For example, Foo() and FooLastResult() implementation relies on the enum // value kFoo. The enum values are used to identify and manage Future in the // Firestore Future manager. enum class QueryFn { // Enum values for the baseclass Query. kGet = 0, // Enum values below are for the subclass CollectionReference. kAdd, // Must be the last enum value. kCount, }; // clang-format off #define QUERY_METHODS(X) \ X(EqualTo, "whereEqualTo", \ "(Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;)" \ "Lcom/google/firebase/firestore/Query;"), \ X(LessThan, "whereLessThan", \ "(Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;)" \ "Lcom/google/firebase/firestore/Query;"), \ X(LessThanOrEqualTo, "whereLessThanOrEqualTo", \ "(Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;)" \ "Lcom/google/firebase/firestore/Query;"), \ X(GreaterThan, "whereGreaterThan", \ "(Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;)" \ "Lcom/google/firebase/firestore/Query;"), \ X(GreaterThanOrEqualTo, "whereGreaterThanOrEqualTo", \ "(Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;)" \ "Lcom/google/firebase/firestore/Query;"), \ X(ArrayContains, "whereArrayContains", \ "(Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;)" \ "Lcom/google/firebase/firestore/Query;"), \ X(ArrayContainsAny, "whereArrayContainsAny", \ "(Lcom/google/firebase/firestore/FieldPath;Ljava/util/List;)" \ "Lcom/google/firebase/firestore/Query;"), \ X(In, "whereIn", \ "(Lcom/google/firebase/firestore/FieldPath;Ljava/util/List;)" \ "Lcom/google/firebase/firestore/Query;"), \ X(OrderBy, "orderBy", \ "(Lcom/google/firebase/firestore/FieldPath;" \ "Lcom/google/firebase/firestore/Query$Direction;)" \ "Lcom/google/firebase/firestore/Query;"), \ X(Limit, "limit", "(J)Lcom/google/firebase/firestore/Query;"), \ X(LimitToLast, "limitToLast", \ "(J)Lcom/google/firebase/firestore/Query;"), \ X(StartAtSnapshot, "startAt", \ "(Lcom/google/firebase/firestore/DocumentSnapshot;)" \ "Lcom/google/firebase/firestore/Query;"), \ X(StartAt, "startAt", \ "([Ljava/lang/Object;)Lcom/google/firebase/firestore/Query;"), \ X(StartAfterSnapshot, "startAfter", \ "(Lcom/google/firebase/firestore/DocumentSnapshot;)" \ "Lcom/google/firebase/firestore/Query;"), \ X(StartAfter, "startAfter", \ "([Ljava/lang/Object;)Lcom/google/firebase/firestore/Query;"), \ X(EndBeforeSnapshot, "endBefore", \ "(Lcom/google/firebase/firestore/DocumentSnapshot;)" \ "Lcom/google/firebase/firestore/Query;"), \ X(EndBefore, "endBefore", \ "([Ljava/lang/Object;)Lcom/google/firebase/firestore/Query;"), \ X(EndAtSnapshot, "endAt", \ "(Lcom/google/firebase/firestore/DocumentSnapshot;)" \ "Lcom/google/firebase/firestore/Query;"), \ X(EndAt, "endAt", \ "([Ljava/lang/Object;)Lcom/google/firebase/firestore/Query;"), \ X(Get, "get", \ "(Lcom/google/firebase/firestore/Source;)" \ "Lcom/google/android/gms/tasks/Task;"), \ X(AddSnapshotListener, "addSnapshotListener", \ "(Lcom/google/firebase/firestore/MetadataChanges;" \ "Lcom/google/firebase/firestore/EventListener;)" \ "Lcom/google/firebase/firestore/ListenerRegistration;") // clang-format on METHOD_LOOKUP_DECLARATION(query, QUERY_METHODS) class QueryInternal : public WrapperFuture<QueryFn, QueryFn::kCount> { public: using ApiType = Query; using WrapperFuture::WrapperFuture; /** Gets the Firestore instance associated with this query. */ Firestore* firestore(); /** * @brief Creates and returns a new Query with the additional filter that * documents must contain the specified field and the value should be equal to * the specified value. * * @param[in] field The path of the field to compare * @param[in] value The value for comparison * * @return The created Query. */ Query WhereEqualTo(const FieldPath& field, const FieldValue& value) { return Where(field, query::kEqualTo, value); } /** * @brief Creates and returns a new Query with the additional filter that * documents must contain the specified field and the value should be less * than the specified value. * * @param[in] field The path of the field to compare * @param[in] value The value for comparison * * @return The created Query. */ Query WhereLessThan(const FieldPath& field, const FieldValue& value) { return Where(field, query::kLessThan, value); } /** * @brief Creates and returns a new Query with the additional filter that * documents must contain the specified field and the value should be less * than or equal to the specified value. * * @param[in] field The path of the field to compare * @param[in] value The value for comparison * * @return The created Query. */ Query WhereLessThanOrEqualTo(const FieldPath& field, const FieldValue& value) { return Where(field, query::kLessThanOrEqualTo, value); } /** * @brief Creates and returns a new Query with the additional filter that * documents must contain the specified field and the value should be greater * than the specified value. * * @param[in] field The path of the field to compare * @param[in] value The value for comparison * * @return The created Query. */ Query WhereGreaterThan(const FieldPath& field, const FieldValue& value) { return Where(field, query::kGreaterThan, value); } /** * @brief Creates and returns a new Query with the additional filter that * documents must contain the specified field and the value should be greater * than or equal to the specified value. * * @param[in] field The path of the field to compare * @param[in] value The value for comparison * * @return The created Query. */ Query WhereGreaterThanOrEqualTo(const FieldPath& field, const FieldValue& value) { return Where(field, query::kGreaterThanOrEqualTo, value); } /** * @brief Creates and returns a new Query with the additional filter that * documents must contain the specified field, the value must be an array, and * that the array must contain the provided value. * * A Query can have only one `WhereArrayContains()` filter. * * @param[in] field The path of the field containing an array to search * @param[in] value The value that must be contained in the array * * @return The created Query. */ Query WhereArrayContains(const FieldPath& field, const FieldValue& value) { return Where(field, query::kArrayContains, value); } /** * @brief Creates and returns a new Query with the additional filter that * documents must contain the specified field, the value must be an array, and * that the array must contain at least one value from the provided list. * * A Query can have only one `WhereArrayContainsAny()` filter and it cannot be * combined with `WhereArrayContains()` or `WhereIn()`. * * @param[in] field The path of the field containing an array to search. * @param[in] values The list that contains the values to match. * * @return The created Query. */ Query WhereArrayContainsAny(const FieldPath& field, const std::vector<FieldValue>& values) { return Where(field, query::kArrayContainsAny, values); } /** * @brief Creates and returns a new Query with the additional filter that * documents must contain the specified field and the value must equal one of * the values from the provided list. * * A Query can have only one `WhereIn()` filter and it cannot be * combined with `WhereArrayContainsAny()`. * * @param[in] field The path of the field containing an array to search. * @param[in] values The list that contains the values to match. * * @return The created Query. */ Query WhereIn(const FieldPath& field, const std::vector<FieldValue>& values) { return Where(field, query::kIn, values); } /** * @brief Creates and returns a new Query that's additionally sorted by the * specified field. * * @param[in] field The field to sort by. * @param[in] direction The direction to sort. * * @return The created Query. */ Query OrderBy(const FieldPath& field, Query::Direction direction); /** * @brief Creates and returns a new Query that only returns the first matching * documents up to the specified number. * * @param[in] limit A non-negative integer to specify the maximum number of * items to return. * * @return The created Query. */ virtual Query Limit(int32_t limit); /** * @brief Creates and returns a new Query that only returns the last matching * documents up to the specified number. * * @param[in] limit A non-negative integer to specify the maximum number of * items to return. * * @return The created Query. */ virtual Query LimitToLast(int32_t limit); /** * @brief Creates and returns a new Query that starts at the provided document * (inclusive). The starting position is relative to the order of the query. * The document must contain all of the fields provided in the OrderBy of this * query. * * @param[in] snapshot The snapshot of the document to start at. * * @return The created Query. */ Query StartAt(const DocumentSnapshot& snapshot) { return WithBound(query::kStartAtSnapshot, snapshot); } /** * @brief Creates and returns a new Query that starts at the provided fields * relative to the order of the query. The order of the field values must * match the order of the order by clauses of the query. * * @param[in] values The field values to start this query at, in order of the * query's order by. * * @return The created Query. */ Query StartAt(const std::vector<FieldValue>& values) { return WithBound(query::kStartAt, values); } /** * @brief Creates and returns a new Query that starts after the provided * document (inclusive). The starting position is relative to the order of the * query. The document must contain all of the fields provided in the OrderBy * of this query. * * @param[in] snapshot The snapshot of the document to start after. * * @return The created Query. */ Query StartAfter(const DocumentSnapshot& snapshot) { return WithBound(query::kStartAfterSnapshot, snapshot); } /** * @brief Creates and returns a new Query that starts after the provided * fields relative to the order of the query. The order of the field values * must match the order of the order by clauses of the query. * * @param[in] values The field values to start this query after, in order of * the query's order by. * * @return The created Query. */ Query StartAfter(const std::vector<FieldValue>& values) { return WithBound(query::kStartAfter, values); } /** * @brief Creates and returns a new Query that ends before the provided * document (inclusive). The end position is relative to the order of the * query. The document must contain all of the fields provided in the OrderBy * of this query. * * @param[in] snapshot The snapshot of the document to end before. * * @return The created Query. */ Query EndBefore(const DocumentSnapshot& snapshot) { return WithBound(query::kEndBeforeSnapshot, snapshot); } /** * @brief Creates and returns a new Query that ends before the provided fields * relative to the order of the query. The order of the field values must * match the order of the order by clauses of the query. * * @param[in] values The field values to end this query before, in order of * the query's order by. * * @return The created Query. */ Query EndBefore(const std::vector<FieldValue>& values) { return WithBound(query::kEndBefore, values); } /** * @brief Creates and returns a new Query that ends at the provided document * (inclusive). The end position is relative to the order of the query. The * document must contain all of the fields provided in the OrderBy of this * query. * * @param[in] snapshot The snapshot of the document to end at. * * @return The created Query. */ Query EndAt(const DocumentSnapshot& snapshot) { return WithBound(query::kEndAtSnapshot, snapshot); } /** * @brief Creates and returns a new Query that ends at the provided fields * relative to the order of the query. The order of the field values must * match the order of the order by clauses of the query. * * @param[in] values The field values to end this query at, in order of the * query's order by. * * @return The created Query. */ Query EndAt(const std::vector<FieldValue>& values) { return WithBound(query::kEndAt, values); } /** * @brief Executes the query and returns the results as a QuerySnapshot. * * By default, Get() attempts to provide up-to-date data when possible by * waiting for data from the server, but it may return cached data or fail if * you are offline and the server cannot be reached. This behavior can be * altered via the {@link Source} parameter. * * @param[in] source A value to configure the get behavior. * * @return A Future that will be resolved with the results of the Query. */ virtual Future<QuerySnapshot> Get(Source source); /** * @brief Gets the result of the most recent call to either of the Get() * methods. * * @return The result of last call to Get() or an invalid Future, if there is * no such call. */ virtual Future<QuerySnapshot> GetLastResult(); #if defined(FIREBASE_USE_STD_FUNCTION) /** * @brief Starts listening to the QuerySnapshot events referenced by this * query. * * @param[in] metadata_changes Indicates whether metadata-only changes (i.e. * only QuerySnapshot.getMetadata() changed) should trigger snapshot events. * @param[in] When this function is called, snapshot value is valid if and * only if error is Error::Ok. * * @return A registration object that can be used to remove the listener. * * @note This method is not available when using the STLPort C++ runtime * library. */ ListenerRegistration AddSnapshotListener( MetadataChanges metadata_changes, std::function<void(const QuerySnapshot&, Error)> callback); #endif // defined(FIREBASE_USE_STD_FUNCTION) /** * @brief Starts listening to the QuerySnapshot events referenced by this * query. * * @param[in] metadata_changes Indicates whether metadata-only changes (i.e. * only QuerySnapshot.getMetadata() changed) should trigger snapshot events. * @param[in] listener The event listener that will be called with the * snapshots, which must remain in memory until you remove the listener from * this Query. (Ownership is not transferred; you are responsible for making * sure that listener is valid as long as this Query is valid and the listener * is registered.) * * @return A registration object that can be used to remove the listener. */ ListenerRegistration AddSnapshotListener( MetadataChanges metadata_changes, EventListener<QuerySnapshot>* listener, bool passing_listener_ownership = false); private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); // A generalized function for all WhereFoo calls. Query Where(const FieldPath& field, query::Method method, const FieldValue& value); Query Where(const FieldPath& field, query::Method method, const std::vector<FieldValue>& values); // A generalized function for all {Start|End}{Before|After|At} calls. Query WithBound(query::Method method, const DocumentSnapshot& snapshot); Query WithBound(query::Method method, const std::vector<FieldValue>& values); // A helper function to convert std::vector<FieldValue> to Java FieldValue[]. jobjectArray ConvertFieldValues(JNIEnv* env, const std::vector<FieldValue>& field_values); }; bool operator==(const QueryInternal& lhs, const QueryInternal& rhs); inline bool operator!=(const QueryInternal& lhs, const QueryInternal& rhs) { return !(lhs == rhs); } } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_QUERY_ANDROID_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_WRAPPER_FUTURE_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_WRAPPER_FUTURE_H_ #include <jni.h> #include "app/meta/move.h" #include "firestore/src/android/promise_android.h" #include "firestore/src/android/wrapper.h" namespace firebase { namespace firestore { // This is a wrapper class that has Future support. EnumType is the enum class // type that identify Future APIs for each subclass and FnCount is the last enum // value of EnumType to represent the number of Future APIs. template <typename EnumType, EnumType FnCount> class WrapperFuture : public Wrapper { public: // A global reference will be created from obj. The caller is responsible for // cleaning up any local references to obj after the constructor returns. WrapperFuture(FirestoreInternal* firestore, jobject obj) : Wrapper(firestore, obj) { firestore_->future_manager().AllocFutureApi(this, static_cast<int>(FnCount)); } WrapperFuture(const WrapperFuture& rhs) : Wrapper(rhs) { firestore_->future_manager().AllocFutureApi(this, static_cast<int>(FnCount)); } WrapperFuture(WrapperFuture&& rhs) : Wrapper(firebase::Move(rhs)) { firestore_->future_manager().MoveFutureApi(&rhs, this); } ~WrapperFuture() override { firestore_->future_manager().ReleaseFutureApi(this); } protected: // Gets the reference-counted Future implementation of this instance, which // can be used to create a Future. ReferenceCountedFutureImpl* ref_future() { return firestore_->future_manager().GetFutureApi(this); } // Creates a Promise representing the completion of an underlying Java Task. // This can be used to implement APIs that return Futures of some public type. // Use MakePromise<void, void>() to create a Future<void>. template <typename PublicType, typename InternalType> Promise<PublicType, InternalType, EnumType> MakePromise() { return Promise<PublicType, InternalType, EnumType>{ref_future(), firestore_}; } // A helper that generalizes the logic for FooLastResult() of each Foo() // defined. template <typename ResultType> Future<ResultType> LastResult(EnumType index) { const auto& result = ref_future()->LastResult(static_cast<int>(index)); return static_cast<const Future<ResultType>&>(result); } }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_WRAPPER_FUTURE_H_ <file_sep>#include "firebase/csharp/unity_transaction_function.h" #include "app/src/assert.h" namespace firebase { namespace firestore { namespace csharp { ::firebase::Mutex* UnityTransactionFunction::mutex_ = new ::firebase::Mutex(); UnityTransactionFunctionCallback UnityTransactionFunction::transaction_function_callback_ = nullptr; Error UnityTransactionFunction::Apply(Transaction* transaction, std::string* error_message) { MutexLock lock(*mutex_); if (transaction_function_callback_ != nullptr) { return transaction_function_callback_(callback_id_, transaction, error_message); } else { FIREBASE_ASSERT_MESSAGE( false, "C++ transaction callback called before C# registered."); return Error::Ok; } } void UnityTransactionFunction::SetCallback( UnityTransactionFunctionCallback callback) { MutexLock lock(*mutex_); if (!callback) { transaction_function_callback_ = nullptr; return; } if (transaction_function_callback_) { FIREBASE_ASSERT(transaction_function_callback_ == callback); } else { transaction_function_callback_ = callback; } } Future<void> UnityTransactionFunction::RunTransactionOn(int32_t callback_id, Firestore* firestore) { UnityTransactionFunction unity_transaction_function(callback_id); return firestore->RunTransaction( [unity_transaction_function](Transaction* transaction, std::string* error_message) mutable { return unity_transaction_function.Apply(transaction, error_message); }); } } // namespace csharp } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_FIELD_PATH_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_FIELD_PATH_ANDROID_H_ #include <jni.h> #include "app/src/include/firebase/app.h" #include "firestore/src/include/firebase/firestore/field_path.h" namespace firebase { namespace firestore { // This helper class provides conversion between the C++ type and Java type. In // addition, we also need proper initializer and terminator for the Java class // cache/uncache. class FieldPathConverter { public: using ApiType = FieldPath; // Convert a C++ FieldPath to a Java FieldPath. static jobject ToJavaObject(JNIEnv* env, const FieldPath& path); // We do not need to convert Java FieldPath back to C++ FieldPath since there // is no public API that returns a FieldPath yet. private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_FIELD_PATH_ANDROID_H_ <file_sep># Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. if(APPLE AND NOT ANDROID) set(settings_apple_SRCS src/common/settings_ios.mm) else() set(settings_apple_SRCS) endif() set(common_SRCS src/common/cleanup.h src/common/collection_reference.cc src/common/document_change.cc src/common/document_reference.cc src/common/document_snapshot.cc src/common/field_path.cc src/common/field_value.cc src/common/firestore.cc src/common/futures.h src/common/listener_registration.cc src/common/main_for_testing_build.cc src/common/query.cc src/common/query_snapshot.cc src/common/set_options.cc src/common/settings.cc src/common/snapshot_metadata.cc src/common/to_string.cc src/common/to_string.h src/common/transaction.cc src/common/util.cc src/common/util.h src/common/write_batch.cc ${settings_apple_SRCS}) # Define the resource build needed for Android firebase_cpp_gradle(":firestore:firestore_resources:generateDexJarRelease" "${CMAKE_CURRENT_LIST_DIR}/firestore_resources/build/dexed.jar") binary_to_array("firestore_resources" "${CMAKE_CURRENT_LIST_DIR}/firestore_resources/build/dexed.jar" "firebase_firestore" "${FIREBASE_GEN_FILE_DIR}/firestore") set(android_SRCS ${firestore_resources_source} src/android/blob_android.cc src/android/blob_android.h src/android/collection_reference_android.cc src/android/collection_reference_android.h src/android/direction_android.cc src/android/direction_android.h src/android/document_change_android.cc src/android/document_change_android.h src/android/document_change_type_android.cc src/android/document_change_type_android.h src/android/document_reference_android.cc src/android/document_reference_android.h src/android/document_snapshot_android.cc src/android/document_snapshot_android.h src/android/event_listener_android.cc src/android/event_listener_android.h src/android/field_path_android.cc src/android/field_path_android.h src/android/field_path_portable.cc src/android/field_path_portable.h src/android/field_value_android.cc src/android/field_value_android.h src/android/firebase_firestore_exception_android.cc src/android/firebase_firestore_exception_android.h src/android/firebase_firestore_settings_android.cc src/android/firebase_firestore_settings_android.h src/android/firestore_android.cc src/android/firestore_android.h src/android/geo_point_android.cc src/android/geo_point_android.h src/android/geo_point_portable.cc src/android/lambda_event_listener.h src/android/lambda_transaction_function.h src/android/listener_registration_android.cc src/android/listener_registration_android.h src/android/metadata_changes_android.cc src/android/metadata_changes_android.h src/android/promise_android.h src/android/query_android.cc src/android/query_android.h src/android/query_snapshot_android.cc src/android/query_snapshot_android.h src/android/server_timestamp_behavior_android.cc src/android/server_timestamp_behavior_android.h src/android/set_options_android.cc src/android/set_options_android.h src/android/snapshot_metadata_android.cc src/android/snapshot_metadata_android.h src/android/source_android.cc src/android/source_android.h src/android/timestamp_android.cc src/android/timestamp_android.h src/android/timestamp_portable.cc src/android/transaction_android.cc src/android/transaction_android.h src/android/util_android.h src/android/wrapper.cc src/android/wrapper.h src/android/wrapper_future.h src/android/write_batch_android.cc src/android/write_batch_android.h) set(ios_SRCS src/ios/collection_reference_ios.cc src/ios/collection_reference_ios.h src/ios/converter_ios.h src/ios/credentials_provider_ios.cc src/ios/credentials_provider_ios.h src/ios/document_change_ios.cc src/ios/document_change_ios.h src/ios/document_reference_ios.cc src/ios/document_reference_ios.h src/ios/document_snapshot_ios.cc src/ios/document_snapshot_ios.h src/ios/field_value_ios.cc src/ios/field_value_ios.h src/ios/firebase_firestore_settings_ios.cc src/ios/firebase_firestore_settings_ios.h src/ios/firestore_ios.cc src/ios/firestore_ios.h src/ios/hard_assert_ios.cc src/ios/hard_assert_ios.h src/ios/listener_ios.h src/ios/listener_registration_ios.cc src/ios/listener_registration_ios.h src/ios/promise_factory_ios.h src/ios/promise_ios.h src/ios/query_ios.cc src/ios/query_ios.h src/ios/query_snapshot_ios.cc src/ios/query_snapshot_ios.h src/ios/set_options_ios.h src/ios/source_ios.h src/ios/transaction_ios.cc src/ios/transaction_ios.h src/ios/user_data_converter_ios.cc src/ios/user_data_converter_ios.h src/ios/util_ios.h src/ios/write_batch_ios.cc src/ios/write_batch_ios.h) set(wrapper_assertions_SRCS src/common/wrapper_assertions.cc src/common/wrapper_assertions.h) if(ANDROID) set(firestore_platform_SRCS "${android_SRCS}") else() # The iOS implementation is actually portable to desktop environments as # well. set(firestore_platform_SRCS "${ios_SRCS}") endif() add_library(firebase_firestore STATIC ${common_SRCS} ${firestore_platform_SRCS}) set_property(TARGET firebase_firestore PROPERTY FOLDER "Firebase Cpp") if(NOT ANDROID) set(firestore_api_dep firebase_firestore_api) else() set(firestore_api_dep) endif() # Set up the dependency on Firebase App. target_link_libraries(firebase_firestore PUBLIC firebase_app firebase_auth PRIVATE ${firestore_api_dep} ) # Public headers all refer to each other relative to the src/include directory, # while private headers are relative to the entire C++ SDK directory. target_include_directories(firebase_firestore PUBLIC ${CMAKE_CURRENT_LIST_DIR}/src/include ${FIRESTORE_SOURCE_DIR}/Firestore/core/include PRIVATE ${FIREBASE_CPP_SDK_ROOT_DIR} ) target_compile_definitions(firebase_firestore PRIVATE -DINTERNAL_EXPERIMENTAL=1 ) if(ANDROID) firebase_cpp_proguard_file(firestore) elseif(IOS) # Enable Automatic Reference Counting (ARC). set_property( TARGET firebase_firestore APPEND_STRING PROPERTY COMPILE_FLAGS "-fobjc-arc") endif() cpp_pack_library(firebase_firestore "") cpp_pack_public_headers() <file_sep># Copyright 2018 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Defines a custom_command to generate source and header files using the # binary_to_array script. Generated files are at NAME_(source/header). # # Args: # NAME: The name to use for the generated files. # INPUT: The input binary to embed into the source file. # CPP_NAMESPACE: The namespace to use in the generated files. # OUTPUT_DIRECTORY: Where the generated files should be written to. function(binary_to_array NAME INPUT CPP_NAMESPACE OUTPUT_DIRECTORY) # Guarantee the output directory exists file(MAKE_DIRECTORY ${OUTPUT_DIRECTORY}) # Define variables for the output source and header for the parent set(output_source "${OUTPUT_DIRECTORY}/${NAME}.cc") set(output_header "${OUTPUT_DIRECTORY}/${NAME}.h") set(${NAME}_source "${output_source}" PARENT_SCOPE) set(${NAME}_header "${output_header}" PARENT_SCOPE) add_custom_command( OUTPUT ${output_source} ${output_header} DEPENDS ${INPUT} COMMAND python "${FIREBASE_SCRIPT_DIR}/binary_to_array.py" "--input=${INPUT}" "--output_header=${output_header}" "--output_source=${output_source}" "--cpp_namespace=${CPP_NAMESPACE}" "--array=${NAME}_data" "--array_size=${NAME}_size" "--filename_identifier=${NAME}_filename" COMMENT "Generating ${NAME}" ) endfunction()<file_sep>// Copyright 2016 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "remote_config/src/common.h" #include <assert.h> #include "app/src/cleanup_notifier.h" #include "app/src/util.h" #include "remote_config/src/include/firebase/remote_config.h" // Register the module initializer. FIREBASE_APP_REGISTER_CALLBACKS(remote_config, { if (app == ::firebase::App::GetInstance()) { return firebase::remote_config::Initialize( *app); } return kInitResultSuccess; }, { if (app == ::firebase::App::GetInstance()) { firebase::remote_config::Terminate(); } }); namespace firebase { namespace remote_config { namespace internal { const char kRemoteConfigModuleName[] = "remote_config"; // Registers a cleanup task for this module if auto-initialization is disabled. void RegisterTerminateOnDefaultAppDestroy() { if (!AppCallback::GetEnabledByName(kRemoteConfigModuleName)) { CleanupNotifier* cleanup_notifier = CleanupNotifier::FindByOwner(App::GetInstance()); assert(cleanup_notifier); cleanup_notifier->RegisterObject( const_cast<char*>(kRemoteConfigModuleName), [](void*) { LogError( "remote_config::Terminate() should be called before default app " "is destroyed."); if (firebase::remote_config::internal::IsInitialized()) { firebase::remote_config::Terminate(); } }); } } // Remove the cleanup task for this module if auto-initialization is disabled. void UnregisterTerminateOnDefaultAppDestroy() { if (!AppCallback::GetEnabledByName(kRemoteConfigModuleName) && firebase::remote_config::internal::IsInitialized()) { CleanupNotifier* cleanup_notifier = CleanupNotifier::FindByOwner(App::GetInstance()); assert(cleanup_notifier); cleanup_notifier->UnregisterObject( const_cast<char*>(kRemoteConfigModuleName)); } } } // namespace internal FutureData* FutureData::s_future_data_; // Create FutureData singleton. FutureData* FutureData::Create() { s_future_data_ = new FutureData(); return s_future_data_; } // Destroy the FutureData singleton. void FutureData::Destroy() { delete s_future_data_; s_future_data_ = nullptr; } // Get the Future data singleton. FutureData* FutureData::Get() { return s_future_data_; } } // namespace remote_config } // namespace firebase <file_sep>#include "firestore/src/ios/transaction_ios.h" #include <future> // NOLINT(build/c++11) #include <utility> #include "firestore/src/ios/converter_ios.h" #include "firestore/src/ios/document_reference_ios.h" #include "firestore/src/ios/field_value_ios.h" #include "firestore/src/ios/hard_assert_ios.h" #include "firestore/src/ios/set_options_ios.h" #include "firestore/src/ios/util_ios.h" #include "absl/types/optional.h" #include "Firestore/core/src/firebase/firestore/core/user_data.h" #include "Firestore/core/src/firebase/firestore/model/document.h" #include "Firestore/core/src/firebase/firestore/model/document_key.h" #include "Firestore/core/src/firebase/firestore/model/field_path.h" #include "Firestore/core/src/firebase/firestore/model/maybe_document.h" #include "Firestore/core/src/firebase/firestore/util/status.h" #include "Firestore/core/src/firebase/firestore/util/statusor.h" namespace firebase { namespace firestore { namespace { using core::ParsedSetData; using core::ParsedUpdateData; using model::Document; using model::MaybeDocument; using util::Status; using util::StatusOr; const model::DocumentKey& GetKey(const DocumentReference& document) { return GetInternal(&document)->key(); } DocumentSnapshot ConvertToSingleSnapshot( const std::shared_ptr<api::Firestore>& firestore, model::DocumentKey key, const std::vector<MaybeDocument>& documents) { HARD_ASSERT_IOS( documents.size() == 1, "Expected core::Transaction::Lookup() to return a single document"); const MaybeDocument& doc = documents.front(); if (doc.is_no_document()) { api::DocumentSnapshot snapshot = api::DocumentSnapshot::FromNoDocument( firestore, key, api::SnapshotMetadata{/*from_cache=*/false, /*has_pending_writes=*/false}); return MakePublic(std::move(snapshot)); } else if (doc.is_document()) { api::DocumentSnapshot snapshot = api::DocumentSnapshot::FromDocument( firestore, Document(doc), api::SnapshotMetadata{/*from_cache=*/false, /*has_pending_writes=*/false}); return MakePublic(std::move(snapshot)); } else { // TODO(b/147444199): use string formatting. // HARD_FAIL( // "core::Transaction::Lookup() returned unexpected document type: // '%s'", doc.type()); auto message = std::string( "core::Transaction::Lookup() returned unexpected " "document type: '") + std::to_string(static_cast<int>(doc.type())) + "'"; HARD_FAIL_IOS(message.c_str()); } } } // namespace TransactionInternal::TransactionInternal( std::shared_ptr<core::Transaction> transaction, FirestoreInternal* firestore_internal) : transaction_{std::move(NOT_NULL(transaction))}, firestore_internal_{NOT_NULL(firestore_internal)}, user_data_converter_{&firestore_internal->database_id()} {} Firestore* TransactionInternal::firestore() { return Firestore::GetInstance(firestore_internal_->app()); } FirestoreInternal* TransactionInternal::firestore_internal() { return firestore_internal_; } void TransactionInternal::Set(const DocumentReference& document, const MapFieldValue& data, const SetOptions& options) { ParsedSetData parsed = user_data_converter_.ParseSetData(data, options); transaction_->Set(GetKey(document), std::move(parsed)); } void TransactionInternal::Update(const DocumentReference& document, const MapFieldValue& data) { transaction_->Update(GetKey(document), user_data_converter_.ParseUpdateData(data)); } void TransactionInternal::Update(const DocumentReference& document, const MapFieldPathValue& data) { transaction_->Update(GetKey(document), user_data_converter_.ParseUpdateData(data)); } void TransactionInternal::Delete(const DocumentReference& document) { transaction_->Delete(GetKey(document)); } DocumentSnapshot TransactionInternal::Get(const DocumentReference& document, Error* error_code, std::string* error_message) { std::promise<StatusOr<DocumentSnapshot>> promise; model::DocumentKey key = GetKey(document); transaction_->Lookup( {key}, [&](const util::StatusOr<std::vector<MaybeDocument>>& maybe_docs) { if (maybe_docs.ok()) { DocumentSnapshot snapshot = ConvertToSingleSnapshot(firestore_internal_->firestore_core(), std::move(key), maybe_docs.ValueOrDie()); promise.set_value(std::move(snapshot)); } else { promise.set_value(maybe_docs.status()); } }); auto future = promise.get_future(); future.wait(); StatusOr<DocumentSnapshot> result = future.get(); if (result.ok()) { if (error_code != nullptr) { *error_code = Error::Ok; } if (error_message != nullptr) { *error_message = ""; } return std::move(result).ValueOrDie(); } else { if (error_code != nullptr) { *error_code = result.status().code(); } if (error_message != nullptr) { *error_message = result.status().error_message(); } return DocumentSnapshot{}; } } void TransactionInternal::MarkPermanentlyFailed() { transaction_->MarkPermanentlyFailed(); } } // namespace firestore } // namespace firebase <file_sep>#include "firestore/src/android/transaction_android.h" #include <jni.h> #include <utility> #include "app/src/embedded_file.h" #include "app/src/include/firebase/internal/common.h" #include "app/src/util_android.h" #include "firestore/src/android/document_reference_android.h" #include "firestore/src/android/field_path_android.h" #include "firestore/src/android/field_value_android.h" #include "firestore/src/android/firebase_firestore_exception_android.h" #include "firestore/src/android/set_options_android.h" namespace firebase { namespace firestore { // clang-format off #define TRANSACTION_METHODS(X) \ X(Set, "set", \ "(Lcom/google/firebase/firestore/DocumentReference;Ljava/lang/Object;" \ "Lcom/google/firebase/firestore/SetOptions;)" \ "Lcom/google/firebase/firestore/Transaction;"), \ X(Update, "update", \ "(Lcom/google/firebase/firestore/DocumentReference;Ljava/util/Map;)" \ "Lcom/google/firebase/firestore/Transaction;"), \ X(UpdateVarargs, "update", \ "(Lcom/google/firebase/firestore/DocumentReference;" \ "Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;" \ "[Ljava/lang/Object;)Lcom/google/firebase/firestore/Transaction;"), \ X(Delete, "delete", "(Lcom/google/firebase/firestore/DocumentReference;)" \ "Lcom/google/firebase/firestore/Transaction;"), \ X(Get, "get", "(Lcom/google/firebase/firestore/DocumentReference;)" \ "Lcom/google/firebase/firestore/DocumentSnapshot;") // clang-format on METHOD_LOOKUP_DECLARATION(transaction, TRANSACTION_METHODS) METHOD_LOOKUP_DEFINITION(transaction, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/Transaction", TRANSACTION_METHODS) #define TRANSACTION_FUNCTION_METHODS(X) X(Constructor, "<init>", "(JJ)V") METHOD_LOOKUP_DECLARATION(transaction_function, TRANSACTION_FUNCTION_METHODS) METHOD_LOOKUP_DEFINITION( transaction_function, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/internal/cpp/TransactionFunction", TRANSACTION_FUNCTION_METHODS) void TransactionInternal::Set(const DocumentReference& document, const MapFieldValue& data, const SetOptions& options) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject data_map = MapFieldValueToJavaMap(firestore_, data); jobject java_options = SetOptionsInternal::ToJavaObject(env, options); env->CallObjectMethod(obj_, transaction::GetMethodId(transaction::kSet), document.internal_->java_object(), data_map, java_options); env->DeleteLocalRef(data_map); env->DeleteLocalRef(java_options); CheckAndClearJniExceptions(); } void TransactionInternal::Update(const DocumentReference& document, const MapFieldValue& data) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject data_map = MapFieldValueToJavaMap(firestore_, data); env->CallObjectMethod(obj_, transaction::GetMethodId(transaction::kUpdate), document.internal_->java_object(), data_map); env->DeleteLocalRef(data_map); CheckAndClearJniExceptions(); } void TransactionInternal::Update(const DocumentReference& document, const MapFieldPathValue& data) { if (data.empty()) { Update(document, MapFieldValue{}); return; } JNIEnv* env = firestore_->app()->GetJNIEnv(); auto iter = data.begin(); jobject first_field = FieldPathConverter::ToJavaObject(env, iter->first); jobject first_value = iter->second.internal_->java_object(); ++iter; // Make the varargs jobjectArray more_fields_and_values = MapFieldPathValueToJavaArray(firestore_, iter, data.end()); env->CallObjectMethod(obj_, transaction::GetMethodId(transaction::kUpdateVarargs), document.internal_->java_object(), first_field, first_value, more_fields_and_values); env->DeleteLocalRef(first_field); env->DeleteLocalRef(more_fields_and_values); CheckAndClearJniExceptions(); } void TransactionInternal::Delete(const DocumentReference& document) { JNIEnv* env = firestore_->app()->GetJNIEnv(); env->CallObjectMethod(obj_, transaction::GetMethodId(transaction::kDelete), document.internal_->java_object()); CheckAndClearJniExceptions(); } DocumentSnapshot TransactionInternal::Get(const DocumentReference& document, Error* error_code, std::string* error_message) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject snapshot = env->CallObjectMethod(obj_, transaction::GetMethodId(transaction::kGet), document.internal_->java_object()); jthrowable exception = env->ExceptionOccurred(); // Now deal with exceptions, if any. Do not preserve yet. Do not call // this->CheckAndClearJniExceptions(). util::CheckAndClearJniExceptions(env); if (exception != nullptr) { if (error_code != nullptr) { *error_code = FirebaseFirestoreExceptionInternal::ToErrorCode(env, exception); } if (error_message != nullptr) { *error_message = FirebaseFirestoreExceptionInternal::ToString(env, exception); } if (!FirebaseFirestoreExceptionInternal::IsInstance(env, exception)) { // We would only preserve exception if it is not // FirebaseFirestoreException. The user should decide whether to raise the // error or let the transaction succeed. PreserveException(exception); } env->DeleteLocalRef(exception); return DocumentSnapshot{}; } else { if (error_code != nullptr) { *error_code = Error::Ok; } if (error_message != nullptr) { *error_message = ""; } } DocumentSnapshot result{new DocumentSnapshotInternal{firestore_, snapshot}}; env->DeleteLocalRef(snapshot); return result; } void TransactionInternal::PreserveException(jthrowable exception) { if (*first_exception_ != nullptr || exception == nullptr) { return; } JNIEnv* env = firestore_->app()->GetJNIEnv(); if (FirebaseFirestoreExceptionInternal::IsFirestoreException(env, exception)) { jobject firestore_exception = FirebaseFirestoreExceptionInternal::ToException(env, exception); *first_exception_ = static_cast<jthrowable>(env->NewGlobalRef(firestore_exception)); env->DeleteLocalRef(firestore_exception); } else { *first_exception_ = static_cast<jthrowable>(env->NewGlobalRef(exception)); } } void TransactionInternal::ClearException() { if (*first_exception_) { firestore_->app()->GetJNIEnv()->DeleteGlobalRef(*first_exception_); *first_exception_ = nullptr; } } bool TransactionInternal::CheckAndClearJniExceptions() { JNIEnv* env = firestore_->app()->GetJNIEnv(); jthrowable exception = env->ExceptionOccurred(); // We need to clear the exception before we can do anything useful. Only limit // JNI APIs have defined behavior when there is an active exception. bool result = util::CheckAndClearJniExceptions(env); PreserveException(exception); return result; } /* static */ jobject TransactionInternal::ToJavaObject(JNIEnv* env, FirestoreInternal* firestore, TransactionFunction* function) { jobject result = env->NewObject( transaction_function::GetClass(), transaction_function::GetMethodId(transaction_function::kConstructor), reinterpret_cast<jlong>(firestore), reinterpret_cast<jlong>(function)); util::CheckAndClearJniExceptions(env); return result; } /* static */ jobject TransactionInternal::TransactionFunctionNativeApply( JNIEnv* env, jclass clazz, jlong firestore_ptr, jlong transaction_function_ptr, jobject transaction) { if (firestore_ptr == 0 || transaction_function_ptr == 0) { return nullptr; } FirestoreInternal* firestore = reinterpret_cast<FirestoreInternal*>(firestore_ptr); TransactionFunction* transaction_function = reinterpret_cast<TransactionFunction*>(transaction_function_ptr); Transaction cpp_transaction(new TransactionInternal{firestore, transaction}); cpp_transaction.internal_->ClearException(); std::string message; Error code = transaction_function->Apply(&cpp_transaction, &message); jobject first_exception = env->NewLocalRef(*(cpp_transaction.internal_->first_exception_)); if (first_exception) { cpp_transaction.internal_->ClearException(); return first_exception; } else { return FirebaseFirestoreExceptionInternal::ToException(env, code, message.c_str()); } } /* static */ bool TransactionInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = transaction::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ bool TransactionInternal::InitializeEmbeddedClasses( App* app, const std::vector<internal::EmbeddedFile>* embedded_files) { static const JNINativeMethod kTransactionFunctionNatives[] = { {"nativeApply", "(JJLcom/google/firebase/firestore/Transaction;)Ljava/lang/Exception;", reinterpret_cast<void*>( &TransactionInternal::TransactionFunctionNativeApply)}}; JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = transaction_function::CacheClassFromFiles(env, activity, embedded_files) && transaction_function::CacheMethodIds(env, activity) && transaction_function::RegisterNatives( env, kTransactionFunctionNatives, FIREBASE_ARRAYSIZE(kTransactionFunctionNatives)); util::CheckAndClearJniExceptions(env); return result; } /* static */ void TransactionInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); transaction::ReleaseClass(env); transaction_function::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_SET_OPTIONS_IOS_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_SET_OPTIONS_IOS_H_ #include <utility> #include "firestore/src/include/firebase/firestore/set_options.h" namespace firebase { namespace firestore { /** * A wrapper over the public `SetOptions` class that allows getting access to * the values stored (the public class only allows setting options, not * retrieving them). */ class SetOptionsInternal { public: using Type = SetOptions::Type; explicit SetOptionsInternal(SetOptions options) : options_{std::move(options)} {} Type type() const { return options_.type_; } const std::vector<FieldPath>& field_mask() const { return options_.fields_; } private: SetOptions options_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_SET_OPTIONS_IOS_H_ <file_sep>// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "remote_config/src/include/firebase/remote_config.h" #include "firebase/app.h" #include "firebase/future.h" #include "remote_config/src/common.h" #include "remote_config/src/desktop/file_manager.h" #include "remote_config/src/desktop/remote_config_desktop.h" #ifndef SWIG #include "firebase/variant.h" #endif // SWIG namespace firebase { namespace remote_config { static const char* kFilePath = "remote_config_data"; static internal::RemoteConfigInternal* g_remote_config_desktop_instance = nullptr; static internal::RemoteConfigFileManager* g_file_manager = nullptr; namespace internal { bool IsInitialized() { return g_remote_config_desktop_instance; } } // namespace internal InitResult Initialize(const App& app) { if (internal::IsInitialized()) return kInitResultSuccess; if (g_remote_config_desktop_instance == nullptr) { if (g_file_manager == nullptr) { g_file_manager = new internal::RemoteConfigFileManager(kFilePath); } FutureData::Create(); g_remote_config_desktop_instance = new internal::RemoteConfigInternal(app, *g_file_manager); } internal::RegisterTerminateOnDefaultAppDestroy(); return kInitResultSuccess; } void Terminate() { if (!internal::IsInitialized()) return; internal::UnregisterTerminateOnDefaultAppDestroy(); delete g_remote_config_desktop_instance; g_remote_config_desktop_instance = nullptr; delete g_file_manager; g_file_manager = nullptr; FutureData::Destroy(); } #ifndef SWIG void SetDefaults(const ConfigKeyValueVariant* defaults, size_t number_of_defaults) { FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized()); g_remote_config_desktop_instance->SetDefaults(defaults, number_of_defaults); } #endif // SWIG void SetDefaults(const ConfigKeyValue* defaults, size_t number_of_defaults) { FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized()); g_remote_config_desktop_instance->SetDefaults(defaults, number_of_defaults); } std::string GetConfigSetting(ConfigSetting setting) { FIREBASE_ASSERT_RETURN(std::string(), internal::IsInitialized()); return g_remote_config_desktop_instance->GetConfigSetting(setting); } void SetConfigSetting(ConfigSetting setting, const char* value) { FIREBASE_ASSERT_RETURN_VOID(internal::IsInitialized()); g_remote_config_desktop_instance->SetConfigSetting(setting, value); } bool GetBoolean(const char* key) { return GetBoolean(key, static_cast<ValueInfo*>(nullptr)); } bool GetBoolean(const char* key, ValueInfo* info) { FIREBASE_ASSERT_RETURN(false, internal::IsInitialized()); return g_remote_config_desktop_instance->GetBoolean(key, info); } int64_t GetLong(const char* key) { return GetLong(key, static_cast<ValueInfo*>(nullptr)); } int64_t GetLong(const char* key, ValueInfo* info) { FIREBASE_ASSERT_RETURN(0, internal::IsInitialized()); return g_remote_config_desktop_instance->GetLong(key, info); } double GetDouble(const char* key) { return GetDouble(key, static_cast<ValueInfo*>(nullptr)); } double GetDouble(const char* key, ValueInfo* info) { FIREBASE_ASSERT_RETURN(0.0, internal::IsInitialized()); return g_remote_config_desktop_instance->GetDouble(key, info); } std::string GetString(const char* key) { return GetString(key, static_cast<ValueInfo*>(nullptr)); } std::string GetString(const char* key, ValueInfo* info) { FIREBASE_ASSERT_RETURN(std::string(), internal::IsInitialized()); return g_remote_config_desktop_instance->GetString(key, info); } std::vector<unsigned char> GetData(const char* key) { return GetData(key, static_cast<ValueInfo*>(nullptr)); } std::vector<unsigned char> GetData(const char* key, ValueInfo* info) { FIREBASE_ASSERT_RETURN(std::vector<unsigned char>(), internal::IsInitialized()); return g_remote_config_desktop_instance->GetData(key, info); } std::vector<std::string> GetKeysByPrefix(const char* prefix) { FIREBASE_ASSERT_RETURN(std::vector<std::string>(), internal::IsInitialized()); return g_remote_config_desktop_instance->GetKeysByPrefix(prefix); } std::vector<std::string> GetKeys() { FIREBASE_ASSERT_RETURN(std::vector<std::string>(), internal::IsInitialized()); return g_remote_config_desktop_instance->GetKeys(); } bool ActivateFetched() { FIREBASE_ASSERT_RETURN(false, internal::IsInitialized()); return g_remote_config_desktop_instance->ActivateFetched(); } const ConfigInfo& GetInfo() { static ConfigInfo config_info; FIREBASE_ASSERT_RETURN(config_info, internal::IsInitialized()); config_info = g_remote_config_desktop_instance->GetInfo(); return config_info; } Future<void> Fetch() { return Fetch(kDefaultCacheExpiration); } Future<void> Fetch(uint64_t cache_expiration_in_seconds) { FIREBASE_ASSERT_RETURN(FetchLastResult(), internal::IsInitialized()); return g_remote_config_desktop_instance->Fetch(cache_expiration_in_seconds); } Future<void> FetchLastResult() { FIREBASE_ASSERT_RETURN(Future<void>(), internal::IsInitialized()); return g_remote_config_desktop_instance->FetchLastResult(); } } // namespace remote_config } // namespace firebase <file_sep>source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' target 'GetPods' do pod 'Firebase/Core', '6.16.0' pod 'Firebase/AdMob', '6.16.0' pod 'Firebase/Analytics', '6.16.0' pod 'Firebase/Auth', '6.16.0' pod 'Firebase/Database', '6.16.0' pod 'Firebase/DynamicLinks', '6.16.0' pod 'Firebase/Functions', '6.16.0' pod 'FirebaseInstanceID', '4.3.0' pod 'Firebase/Messaging', '6.16.0' pod 'Firebase/RemoteConfig', '6.16.0' pod 'Firebase/Storage', '6.16.0' pod 'Crashlytics', '3.14.0' end <file_sep>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef FIREBASE_REMOTE_CONFIG_CLIENT_CPP_SRC_DESKTOP_REST_NANOPB_DECODE_H_ #define FIREBASE_REMOTE_CONFIG_CLIENT_CPP_SRC_DESKTOP_REST_NANOPB_DECODE_H_ #include <string> #include <vector> // Needed because of direct use of enum from generated header. #include "remote_config/config.pb.h" namespace firebase { namespace remote_config { namespace internal { // All of these structs are meant to store data from the proto, one-to-one. // src_protos/config.proto struct KeyValue { std::string key; std::string value; }; struct AppNamespaceConfig { // namespace is the source of the configuration included in this message. std::string config_namespace; std::string digest; std::vector<KeyValue> key_values; desktop_config_AppNamespaceConfigTable_NamespaceStatus status; }; struct AppConfig { // This represents the package name. std::string app_name; // Holds per namespace configuration for this app. // if the app has no configuration defined, then this field will be empty. std::vector<AppNamespaceConfig> ns_configs; }; struct ConfigFetchResponse { // holds all configuration data to be sent to the fetching device. std::vector<AppConfig> configs; }; bool DecodeResponse(ConfigFetchResponse* destination, const std::string& proto_str); } // namespace internal } // namespace remote_config } // namespace firebase #endif // FIREBASE_REMOTE_CONFIG_CLIENT_CPP_SRC_DESKTOP_REST_NANOPB_DECODE_H_ <file_sep>#include "firestore/src/android/write_batch_android.h" #include <jni.h> #include <utility> #include "app/src/util_android.h" #include "firestore/src/android/document_reference_android.h" #include "firestore/src/android/field_path_android.h" #include "firestore/src/android/field_value_android.h" #include "firestore/src/android/set_options_android.h" #include "firestore/src/android/util_android.h" namespace firebase { namespace firestore { // clang-format off #define WRITE_BATCH_METHODS(X) \ X(Set, "set", \ "(Lcom/google/firebase/firestore/DocumentReference;Ljava/lang/Object;" \ "Lcom/google/firebase/firestore/SetOptions;)" \ "Lcom/google/firebase/firestore/WriteBatch;"), \ X(Update, "update", \ "(Lcom/google/firebase/firestore/DocumentReference;Ljava/util/Map;)" \ "Lcom/google/firebase/firestore/WriteBatch;"), \ X(UpdateVarargs, "update", \ "(Lcom/google/firebase/firestore/DocumentReference;" \ "Lcom/google/firebase/firestore/FieldPath;Ljava/lang/Object;" \ "[Ljava/lang/Object;)Lcom/google/firebase/firestore/WriteBatch;"), \ X(Delete, "delete", "(Lcom/google/firebase/firestore/DocumentReference;)" \ "Lcom/google/firebase/firestore/WriteBatch;"), \ X(Commit, "commit", "()Lcom/google/android/gms/tasks/Task;") // clang-format on METHOD_LOOKUP_DECLARATION(write_batch, WRITE_BATCH_METHODS) METHOD_LOOKUP_DEFINITION(write_batch, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/WriteBatch", WRITE_BATCH_METHODS) void WriteBatchInternal::Set(const DocumentReference& document, const MapFieldValue& data, const SetOptions& options) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject data_map = MapFieldValueToJavaMap(firestore_, data); jobject java_options = SetOptionsInternal::ToJavaObject(env, options); env->CallObjectMethod(obj_, write_batch::GetMethodId(write_batch::kSet), document.internal_->java_object(), data_map, java_options); env->DeleteLocalRef(data_map); env->DeleteLocalRef(java_options); CheckAndClearJniExceptions(env); } void WriteBatchInternal::Update(const DocumentReference& document, const MapFieldValue& data) { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject data_map = MapFieldValueToJavaMap(firestore_, data); env->CallObjectMethod(obj_, write_batch::GetMethodId(write_batch::kUpdate), document.internal_->java_object(), data_map); env->DeleteLocalRef(data_map); CheckAndClearJniExceptions(env); } void WriteBatchInternal::Update(const DocumentReference& document, const MapFieldPathValue& data) { if (data.empty()) { Update(document, MapFieldValue{}); return; } JNIEnv* env = firestore_->app()->GetJNIEnv(); auto iter = data.begin(); jobject first_field = FieldPathConverter::ToJavaObject(env, iter->first); jobject first_value = iter->second.internal_->java_object(); ++iter; // Make the varargs jobjectArray more_fields_and_values = MapFieldPathValueToJavaArray(firestore_, iter, data.end()); env->CallObjectMethod(obj_, write_batch::GetMethodId(write_batch::kUpdateVarargs), document.internal_->java_object(), first_field, first_value, more_fields_and_values); env->DeleteLocalRef(first_field); env->DeleteLocalRef(more_fields_and_values); CheckAndClearJniExceptions(env); } void WriteBatchInternal::Delete(const DocumentReference& document) { JNIEnv* env = firestore_->app()->GetJNIEnv(); env->CallObjectMethod(obj_, write_batch::GetMethodId(write_batch::kDelete), document.internal_->java_object()); CheckAndClearJniExceptions(env); } Future<void> WriteBatchInternal::Commit() { JNIEnv* env = firestore_->app()->GetJNIEnv(); jobject task = env->CallObjectMethod( obj_, write_batch::GetMethodId(write_batch::kCommit)); CheckAndClearJniExceptions(env); auto promise = MakePromise<void, void>(); promise.RegisterForTask(WriteBatchFn::kCommit, task); env->DeleteLocalRef(task); CheckAndClearJniExceptions(env); return promise.GetFuture(); } Future<void> WriteBatchInternal::CommitLastResult() { return LastResult<void>(WriteBatchFn::kCommit); } /* static */ bool WriteBatchInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = write_batch::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void WriteBatchInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); write_batch::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>#include "firestore/src/ios/listener_registration_ios.h" #include <utility> #include "app/src/assert.h" namespace firebase { namespace firestore { ListenerRegistrationInternal::ListenerRegistrationInternal( std::unique_ptr<api::ListenerRegistration> registration, FirestoreInternal* firestore) : registration_{std::move(registration)}, firestore_{firestore} { firestore->RegisterListenerRegistration(this); } ListenerRegistrationInternal::~ListenerRegistrationInternal() { Remove(); } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_QUERY_SNAPSHOT_STUB_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_QUERY_SNAPSHOT_STUB_H_ #include <cstddef> #include <vector> #include "firestore/src/include/firebase/firestore/document_change.h" #include "firestore/src/include/firebase/firestore/metadata_changes.h" #include "firestore/src/include/firebase/firestore/query.h" #include "firestore/src/include/firebase/firestore/query_snapshot.h" #include "firestore/src/include/firebase/firestore/snapshot_metadata.h" #include "firestore/src/stub/firestore_stub.h" namespace firebase { namespace firestore { class QuerySnapshotInternal { public: using ApiType = QuerySnapshot; FirestoreInternal* firestore_internal() { return nullptr; } Query query() const { return Query{}; } SnapshotMetadata metadata() const { return SnapshotMetadata{/*has_pending_writes=*/false, /*is_from_cache=*/false}; } std::vector<DocumentChange> DocumentChanges( MetadataChanges metadata_changes) const { return {}; } std::vector<DocumentSnapshot> documents() const { return {}; } std::size_t size() const { return 0; } }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_STUB_QUERY_SNAPSHOT_STUB_H_ <file_sep>#include "firestore/src/android/server_timestamp_behavior_android.h" namespace firebase { namespace firestore { using ServerTimestampBehavior = DocumentSnapshot::ServerTimestampBehavior; // clang-format off #define SERVER_TIMESTAMP_BEHAVIOR_METHODS(X) \ X(Name, "name", "()Ljava/lang/String;") #define SERVER_TIMESTAMP_BEHAVIOR_FIELDS(X) \ X(None, "NONE", \ "Lcom/google/firebase/firestore/DocumentSnapshot$" \ "ServerTimestampBehavior;", \ util::kFieldTypeStatic), \ X(Estimate, "ESTIMATE", \ "Lcom/google/firebase/firestore/DocumentSnapshot$" \ "ServerTimestampBehavior;", \ util::kFieldTypeStatic), \ X(Previous, "PREVIOUS", \ "Lcom/google/firebase/firestore/DocumentSnapshot$" \ "ServerTimestampBehavior;", \ util::kFieldTypeStatic), \ X(Default, "DEFAULT", \ "Lcom/google/firebase/firestore/DocumentSnapshot$" \ "ServerTimestampBehavior;", \ util::kFieldTypeStatic) // clang-format on METHOD_LOOKUP_DECLARATION(server_timestamp_behavior, SERVER_TIMESTAMP_BEHAVIOR_METHODS, SERVER_TIMESTAMP_BEHAVIOR_FIELDS) METHOD_LOOKUP_DEFINITION(server_timestamp_behavior, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/DocumentSnapshot$" "ServerTimestampBehavior", SERVER_TIMESTAMP_BEHAVIOR_METHODS, SERVER_TIMESTAMP_BEHAVIOR_FIELDS) std::map<ServerTimestampBehavior, jobject>* ServerTimestampBehaviorInternal::cpp_enum_to_java_ = nullptr; /* static */ jobject ServerTimestampBehaviorInternal::ToJavaObject( JNIEnv* env, ServerTimestampBehavior stb) { return (*cpp_enum_to_java_)[stb]; } /* static */ bool ServerTimestampBehaviorInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = server_timestamp_behavior::CacheMethodIds(env, activity) && server_timestamp_behavior::CacheFieldIds(env, activity); util::CheckAndClearJniExceptions(env); // Cache Java enum values. cpp_enum_to_java_ = new std::map<ServerTimestampBehavior, jobject>(); const auto add_enum = [env](ServerTimestampBehavior stb, server_timestamp_behavior::Field field) { jobject value = env->GetStaticObjectField(server_timestamp_behavior::GetClass(), server_timestamp_behavior::GetFieldId(field)); (*cpp_enum_to_java_)[stb] = env->NewGlobalRef(value); env->DeleteLocalRef(value); util::CheckAndClearJniExceptions(env); }; add_enum(ServerTimestampBehavior::kDefault, server_timestamp_behavior::kDefault); add_enum(ServerTimestampBehavior::kNone, server_timestamp_behavior::kNone); add_enum(ServerTimestampBehavior::kEstimate, server_timestamp_behavior::kEstimate); add_enum(ServerTimestampBehavior::kPrevious, server_timestamp_behavior::kPrevious); return result; } /* static */ void ServerTimestampBehaviorInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); server_timestamp_behavior::ReleaseClass(env); util::CheckAndClearJniExceptions(env); // Uncache Java enum values. for (auto& kv : *cpp_enum_to_java_) { env->DeleteGlobalRef(kv.second); } util::CheckAndClearJniExceptions(env); delete cpp_enum_to_java_; cpp_enum_to_java_ = nullptr; } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_SNAPSHOT_METADATA_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_SNAPSHOT_METADATA_ANDROID_H_ #include <jni.h> #include "app/src/include/firebase/app.h" #include "firestore/src/include/firebase/firestore/snapshot_metadata.h" namespace firebase { namespace firestore { // This is the non-wrapper Android implementation of SnapshotMetadata. Since // SnapshotMetadata has all methods inlined, we use it directly instead of // wrapping around a Java SnapshotMetadata object. We still need the helper // functions to convert between the two types. In addition, we also need proper // initializer and terminator for the Java class cache/uncache. class SnapshotMetadataInternal { public: using ApiType = SnapshotMetadata; // Convert a C++ SnapshotMetadata into a Java SnapshotMetadata. static jobject SnapshotMetadataToJavaSnapshotMetadata( JNIEnv* env, const SnapshotMetadata& metadata); // Convert a Java SnapshotMetadata into a C++ SnapshotMetadata and release the // reference to the jobject. static SnapshotMetadata JavaSnapshotMetadataToSnapshotMetadata(JNIEnv* env, jobject obj); private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_SNAPSHOT_METADATA_ANDROID_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_TYPEMAP_HELPER_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_TYPEMAP_HELPER_H_ #include <string> #include "firebase/firestore/document_reference.h" #include "firebase/firestore/document_snapshot.h" #include "firebase/firestore/transaction.h" #include "firebase/firestore/firestore_errors.h" // We add helpers to do the type-mapping in C++ code instead of doing this in // SWIG. We want to minimize the SWIG code, which is hard to understand and // debug. namespace firebase { namespace firestore { namespace csharp { struct TransactionGetResult { DocumentSnapshot snapshot; Error error_code = Unknown; std::string error_message; }; TransactionGetResult TransactionGet(Transaction* transaction, const DocumentReference& document) { TransactionGetResult result; result.snapshot = transaction->Get(document, &result.error_code, &result.error_message); return result; } } // namespace csharp } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_INCLUDE_FIREBASE_CSHARP_TYPEMAP_HELPER_H_ <file_sep>#include "firestore/src/android/wrapper.h" #include <iterator> #include "app/src/assert.h" #include "firestore/src/android/field_path_android.h" #include "firestore/src/android/field_value_android.h" #include "firestore/src/android/util_android.h" #include "firestore/src/include/firebase/firestore.h" namespace firebase { namespace firestore { // clang-format off #define OBJECT_METHOD(X) X(Equals, "equals", "(Ljava/lang/Object;)Z") // clang-format on METHOD_LOOKUP_DECLARATION(object, OBJECT_METHOD) METHOD_LOOKUP_DEFINITION(object, "java/lang/Object", OBJECT_METHOD) Wrapper::Wrapper(FirestoreInternal* firestore, jobject obj) : Wrapper(firestore, obj, AllowNullObject::Yes) { FIREBASE_ASSERT(obj != nullptr); } Wrapper::Wrapper(jclass clazz, jmethodID method_id, ...) { // Set firestore_. Firestore* firestore = Firestore::GetInstance(); FIREBASE_ASSERT(firestore != nullptr); firestore_ = firestore->internal_; FIREBASE_ASSERT(firestore_ != nullptr); // Create a jobject. JNIEnv* env = firestore_->app()->GetJNIEnv(); va_list args; va_start(args, method_id); jobject obj = env->NewObjectV(clazz, method_id, args); va_end(args); CheckAndClearJniExceptions(env); // Set obj_, FIREBASE_ASSERT(obj != nullptr); obj_ = env->NewGlobalRef(obj); env->DeleteLocalRef(obj); } Wrapper::Wrapper(const Wrapper& wrapper) : Wrapper(wrapper.firestore_, wrapper.obj_, AllowNullObject::Yes) {} Wrapper::Wrapper(Wrapper&& wrapper) noexcept : firestore_(wrapper.firestore_), obj_(wrapper.obj_) { FIREBASE_ASSERT(firestore_ != nullptr); wrapper.obj_ = nullptr; } Wrapper::Wrapper() : obj_(nullptr) { Firestore* firestore = Firestore::GetInstance(); FIREBASE_ASSERT(firestore != nullptr); firestore_ = firestore->internal_; FIREBASE_ASSERT(firestore_ != nullptr); } Wrapper::Wrapper(Wrapper* rhs) : Wrapper() { if (rhs) { firestore_ = rhs->firestore_; FIREBASE_ASSERT(firestore_ != nullptr); obj_ = firestore_->app()->GetJNIEnv()->NewGlobalRef(rhs->obj_); } } Wrapper::Wrapper(FirestoreInternal* firestore, jobject obj, AllowNullObject) : firestore_(firestore), // NewGlobalRef() is supposed to accept Null Java object and return Null, // which happens to be nullptr in C++. obj_(firestore->app()->GetJNIEnv()->NewGlobalRef(obj)) {} Wrapper::~Wrapper() { if (obj_ != nullptr) { firestore_->app()->GetJNIEnv()->DeleteGlobalRef(obj_); obj_ = nullptr; } } bool Wrapper::EqualsJavaObject(const Wrapper& other) const { if (obj_ == other.obj_) { return true; } JNIEnv* env = firestore_->app()->GetJNIEnv(); jboolean result = env->CallBooleanMethod( obj_, object::GetMethodId(object::kEquals), other.obj_); CheckAndClearJniExceptions(env); return static_cast<bool>(result); } /* static */ jobject Wrapper::MapFieldValueToJavaMap(FirestoreInternal* firestore, const MapFieldValue& data) { JNIEnv* env = firestore->app()->GetJNIEnv(); // Creates an empty Java HashMap (implementing Map) object. jobject result = env->NewObject(util::hash_map::GetClass(), util::hash_map::GetMethodId(util::hash_map::kConstructor)); CheckAndClearJniExceptions(env); // Adds each mapping. jmethodID put_method = util::map::GetMethodId(util::map::kPut); for (const auto& kv : data) { jobject key = env->NewStringUTF(kv.first.c_str()); // Map::Put() returns previously associated value or null, which we have // no use of. env->CallObjectMethod(result, put_method, key, kv.second.internal_->java_object()); env->DeleteLocalRef(key); CheckAndClearJniExceptions(env); } return result; } /* static */ jobjectArray Wrapper::MapFieldPathValueToJavaArray( FirestoreInternal* firestore, MapFieldPathValue::const_iterator begin, MapFieldPathValue::const_iterator end) { JNIEnv* env = firestore->app()->GetJNIEnv(); const auto size = std::distance(begin, end) * 2; jobjectArray result = env->NewObjectArray(size, util::object::GetClass(), /*initialElement=*/nullptr); CheckAndClearJniExceptions(env); int index = 0; for (auto iter = begin; iter != end; ++iter) { jobject field = FieldPathConverter::ToJavaObject(env, iter->first); env->SetObjectArrayElement(result, index, field); env->DeleteLocalRef(field); ++index; env->SetObjectArrayElement(result, index, iter->second.internal_->java_object()); ++index; CheckAndClearJniExceptions(env); } return result; } /* static */ bool Wrapper::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = object::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void Wrapper::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); object::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_DOCUMENT_CHANGE_IOS_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_DOCUMENT_CHANGE_IOS_H_ #include <cstdint> #include "firestore/src/include/firebase/firestore/document_change.h" #include "firestore/src/ios/firestore_ios.h" #include "Firestore/core/src/firebase/firestore/api/document_change.h" namespace firebase { namespace firestore { class DocumentChangeInternal { public: explicit DocumentChangeInternal(api::DocumentChange&& change); FirestoreInternal* firestore_internal(); DocumentChange::Type type() const; DocumentSnapshot document() const; std::size_t old_index() const; std::size_t new_index() const; private: api::DocumentChange change_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_IOS_DOCUMENT_CHANGE_IOS_H_ <file_sep>// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "instance_id/src/include/firebase/instance_id.h" #include <cstdint> #include <string> #include "app/src/include/firebase/version.h" #include "instance_id/src/instance_id_internal.h" namespace firebase { namespace instance_id { Mutex g_instance_ids_lock; // NOLINT // Wildcard scope for FCM token retrieval. static const char* const kScopeAll = "*"; DEFINE_FIREBASE_VERSION_STRING(FirebaseInstanceId); using internal::InstanceIdInternal; InstanceId::InstanceId(App* app, InstanceIdInternal* instance_id_internal) : app_(app), instance_id_internal_(instance_id_internal) { MutexLock lock(g_instance_ids_lock); InstanceIdInternal::RegisterInstanceIdForApp(app_, this); } InstanceId::~InstanceId() { DeleteInternal(); } void InstanceId::DeleteInternal() { MutexLock lock(g_instance_ids_lock); if (!instance_id_internal_) return; InstanceIdInternal::UnregisterInstanceIdForApp(app_, this); delete instance_id_internal_; instance_id_internal_ = nullptr; app_ = nullptr; } Future<std::string> InstanceId::GetIdLastResult() const { return instance_id_internal_ ? static_cast<const Future<std::string>&>( instance_id_internal_->future_api().LastResult( InstanceIdInternal::kApiFunctionGetId)) : Future<std::string>(); } Future<void> InstanceId::DeleteIdLastResult() const { return instance_id_internal_ ? static_cast<const Future<void>&>( instance_id_internal_->future_api().LastResult( InstanceIdInternal::kApiFunctionDeleteId)) : Future<void>(); } Future<std::string> InstanceId::GetToken() { return instance_id_internal_ ? GetToken(app_->options().messaging_sender_id(), kScopeAll) : Future<std::string>(); } Future<std::string> InstanceId::GetTokenLastResult() const { return instance_id_internal_ ? static_cast<const Future<std::string>&>( instance_id_internal_->future_api().LastResult( InstanceIdInternal::kApiFunctionGetToken)) : Future<std::string>(); } Future<void> InstanceId::DeleteToken() { return instance_id_internal_ ? DeleteToken(app_->options().messaging_sender_id(), kScopeAll) : Future<void>(); } Future<void> InstanceId::DeleteTokenLastResult() const { return instance_id_internal_ ? static_cast<const Future<void>&>( instance_id_internal_->future_api().LastResult( InstanceIdInternal::kApiFunctionDeleteToken)) : Future<void>(); } } // namespace instance_id } // namespace firebase <file_sep># Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Used to generate the build_type header used in the C++ build. Generates the build_type header file with the given build type definition. """ from absl import app from absl import flags from absl import logging FLAGS = flags.FLAGS flags.DEFINE_string("output_file", None, "Location of the output file") flags.DEFINE_string("build_type", "FIREBASE_CPP_BUILD_TYPE_RELEASED", "The build type definition to generate with.") BUILD_TYPE_TEMPLATE = """\ // Copyright 2017 Google Inc. All Rights Reserved. #ifndef FIREBASE_APP_CLIENT_CPP_SRC_BUILD_TYPE_H_ #define FIREBASE_APP_CLIENT_CPP_SRC_BUILD_TYPE_H_ // Available build configurations for the suite of libraries. #define FIREBASE_CPP_BUILD_TYPE_HEAD 0 #define FIREBASE_CPP_BUILD_TYPE_STABLE 1 #define FIREBASE_CPP_BUILD_TYPE_RELEASED 2 // Currently selected build type. #define FIREBASE_CPP_BUILD_TYPE {build_type} #endif // FIREBASE_APP_CLIENT_CPP_SRC_BUILD_TYPE_H_ """ def generate_header(build_type): """Return a C/C++ header for the given build type. Args: build_type: The build type definition to use. Returns: A string containing the C/C++ header file. """ return BUILD_TYPE_TEMPLATE.format(build_type=build_type) def main(unused_argv): output_file = FLAGS.output_file if not output_file: output_file = "build_type_generated.h" logging.debug("Using default --output_file='%s'", output_file) with open(output_file, "w") as outfile: outfile.write(generate_header(FLAGS.build_type)) if __name__ == "__main__": app.run(main) <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_SOURCE_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_SOURCE_ANDROID_H_ #include <map> #include "app/src/include/firebase/app.h" #include "app/src/util_android.h" #include "firestore/src/include/firebase/firestore/source.h" namespace firebase { namespace firestore { class SourceInternal { public: static jobject ToJavaObject(JNIEnv* env, Source source); private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); static std::map<Source, jobject>* cpp_enum_to_java_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_SOURCE_ANDROID_H_ <file_sep>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef FIREBASE_DATABASE_CLIENT_CPP_SRC_DESKTOP_REST_INTERFACE_H_ #define FIREBASE_DATABASE_CLIENT_CPP_SRC_DESKTOP_REST_INTERFACE_H_ #include <string> #include "app/rest/controller_interface.h" #include "app/rest/response.h" #include "app/src/include/firebase/future.h" #include "app/src/include/firebase/variant.h" #include "app/src/logger.h" #include "app/src/path.h" #include "app/src/reference_counted_future_impl.h" #include "app/src/semaphore.h" #include "database/src/common/query_spec.h" #include "database/src/include/firebase/database/common.h" #include "database/src/include/firebase/database/listener.h" namespace firebase { namespace database { namespace internal { typedef int64_t WriteId; class DatabaseInternal; class SseResponse : public rest::Response { public: SseResponse() : semaphore_(0) {} virtual ~SseResponse() {} void MarkCompleted() override; void MarkCanceled() override; virtual void Finalize(); void WaitForCompletion(); private: Semaphore semaphore_; }; class QueryResponse : public SseResponse { public: QueryResponse(DatabaseInternal* database, ChildListener* child_listener, const QuerySpec& query_spec) : SseResponse(), database_(database), value_listener_(nullptr), child_listener_(child_listener), query_spec_(query_spec), error_(kErrorNone), error_string_() {} QueryResponse(DatabaseInternal* database, ValueListener* value_listener, const QuerySpec& query_spec) : SseResponse(), database_(database), value_listener_(value_listener), child_listener_(nullptr), query_spec_(query_spec), error_(kErrorNone), error_string_() {} virtual ~QueryResponse(); bool ProcessBody(const char* buffer, size_t length) override; void MarkCompleted() override; void MarkCanceled() override; void Finalize() override; ValueListener* value_listener() { return value_listener_; } ChildListener* child_listener() { return child_listener_; } Variant& data() { return data_; } const QuerySpec& query_spec() const { return query_spec_; } Mutex& mutex() { return mutex_; } void ClearListener(); private: DatabaseInternal* database_; ValueListener* value_listener_; ChildListener* child_listener_; QuerySpec query_spec_; Variant data_; Error error_; std::string error_string_; // Used to guard listener_ Mutex mutex_; }; class SetValueResponse : public rest::Response { public: SetValueResponse(DatabaseInternal* database, const Path& path, SafeFutureHandle<void> handle, ReferenceCountedFutureImpl* ref_future, WriteId write_id); bool ProcessBody(const char* buffer, size_t length) override; void MarkCompleted() override; void MarkCanceled() override; private: DatabaseInternal* database_; Path path_; SafeFutureHandle<void> handle_; ReferenceCountedFutureImpl* ref_future_; WriteId write_id_; Error error_; std::string error_string_; }; using RemoveValueResponse = SetValueResponse; using SetPriorityResponse = SetValueResponse; using SetValueAndPriorityResponse = SetValueResponse; using UpdateChildrenResponse = SetValueResponse; class SingleValueListener : public ValueListener { public: SingleValueListener(DatabaseInternal* database, ReferenceCountedFutureImpl* future, SafeFutureHandle<DataSnapshot> handle); // Unregister ourselves from the database. ~SingleValueListener() override; void OnValueChanged(const DataSnapshot& snapshot) override; void OnCancelled(const Error& error_code, const char* error_message) override; private: DatabaseInternal* database_; ReferenceCountedFutureImpl* future_; SafeFutureHandle<DataSnapshot> handle_; }; class GetValueResponse : public rest::Response { public: GetValueResponse(DatabaseInternal* database, const Path& path, SafeFutureHandle<DataSnapshot> handle, ReferenceCountedFutureImpl* future, SingleValueListener** single_value_listener_holder) : database_(database), path_(path), handle_(handle), future_(future), single_value_listener_holder_(single_value_listener_holder) {} void MarkCompleted() override; private: DatabaseInternal* database_; Path path_; SafeFutureHandle<DataSnapshot> handle_; ReferenceCountedFutureImpl* future_; SingleValueListener** single_value_listener_holder_; }; enum ParseStatus { // The incoming data was successfully parsed, we should pass the results to // the listener. kParseSuccess, // This was just a keep-alive message. We shouldn't do anything with the data, // but we shouldn't report an error either. kParseKeepAlive, // There was an error parsing the data. This listener might have been // canceled, or the authorization was revoked, or the data received was // malformed. kParseError, }; ParseStatus ParseResponse(const std::string& body, Path* out_relative_path, Variant* out_diff, bool* is_overwrite, Error* out_error, std::string* out_error_string); void RestCall(DatabaseInternal* database, const std::string& url, const char* method, const std::string& post_fields, rest::Response* response); void SseRestCall(DatabaseInternal* database, const QuerySpec& query_spec, const char* url, SseResponse* response, flatbuffers::unique_ptr<rest::Controller>* controller_out); struct QueryUrlOptions { enum UrlType { kValueUrl, kPriorityUrl, kValuePriorityUrl }; enum UseAuthToken { kNoToken, kIncludeAuthToken }; QueryUrlOptions(UrlType _url_type, UseAuthToken _use_auth_token, const QuerySpec* _query_spec) : url_type(_url_type), use_auth_token(_use_auth_token), query_spec(_query_spec) {} // Use the priority url instead of the standard one. This is used when setting // or getting the priority value at a location. UrlType url_type; // Whether the auth token should be appended to the URL. UseAuthToken use_auth_token; // Add query args (such as orderBy, limits, etc) if a QuerySpec is present. const QuerySpec* query_spec; }; extern const QueryUrlOptions kJustUrlOptions; extern const QueryUrlOptions kAuthorizedUrlOptions; extern const QueryUrlOptions kAuthorizedPriorityUrlOptions; // Returns the URL to this location in the database, according to the options // supplied. The resulting URL will be the concatenation of the database URL // given by the App object, followed by a slash, followed the full path to the // value this query represents and either '.json' or '/.priority.json' // depending on whether the options specified a priority location. Finally, // the URL arguments are appened, including the Auth token (if present). This // URL is valid for both Query operations as well as DatabaseReference // operations. // // An example URL might look like this: // // https://[PROJECT_ID].firebaseio.com/path/to/object.json?orderBy="height"&startAt=3 // // See https://firebase.google.com/docs/reference/rest/database/ for more // details. std::string GetUrlWithQuery(const QueryUrlOptions& options, DatabaseInternal* database, const QuerySpec& query_spec); } // namespace internal } // namespace database } // namespace firebase #endif // FIREBASE_DATABASE_CLIENT_CPP_SRC_DESKTOP_REST_INTERFACE_H_ <file_sep>// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // This file defines a stand-alone no-op native Android app. The app deals with // app events and do nothing interesting. This app is the one under Android // instrumented test. // // In addition, this file also contains an Android native function to be called // in the Android instrumented test directly. The native function will run all // gtest tests and update information on passed tests. #include <android/log.h> #include <android_native_app_glue.h> #include <jni.h> #include <pthread.h> #include <cassert> #include <cstdarg> #include <cstdio> #include <cstdlib> #include <iostream> #include <memory> #include <sstream> // non-google3 code should include "firebase/app.h" instead. #include "app/src/include/firebase/app.h" #include "app/src/assert.h" #include "firestore/src/include/firebase/firestore.h" #include "firestore/src/android/firestore_android.h" // non-google3 code should include "gtest/gtest.h" instead. #include "gtest/gtest.h" // For GTEST_FLAG(filter). #include "third_party/googletest/googletest/src/gtest-internal-inl.h" #ifndef NATIVE_FUNCTION_NAME #define NATIVE_FUNCTION_NAME Java_com_google_firebase_test_MyTest_RunAllTest #endif // NATIVE_FUNCTION_NAME #define STRINGIFY_(X) #X #define STRINGIFY(X) STRINGIFY_(X) // Preserve the JNIEnv and activity that are required by the Firestore client. static JNIEnv* g_env = nullptr; static jobject g_activity = nullptr; static int g_stdout_pipe_file[2]; static int g_stderr_pipe_file[2]; static pthread_t g_pipe_stdout_thread; static pthread_t g_pipe_stderr_thread; // This implementation is derived from http://github.com/google/fplutil static struct android_app* g_app_state = nullptr; static bool g_destroy_requested = false; static bool g_started = false; static bool g_restarted = false; static pthread_mutex_t g_started_mutex; static void* pipe_thread(void* pipe) { int* pipe_file = static_cast<int*>(pipe); char buffer[256]; const char* tag = pipe_file == g_stdout_pipe_file ? "stdout" : "stderr"; size_t read_size = read(pipe_file[0], buffer, sizeof(buffer) - 1); while (read_size > 0) { // Remove trailing \n. if (buffer[read_size - 1] == '\n') buffer[read_size - 1] = '\0'; __android_log_print(ANDROID_LOG_INFO, tag, "%s", buffer); read_size = read(pipe_file[0], buffer, sizeof(buffer) - 1); } return nullptr; } namespace firebase { namespace firestore { App* GetApp(const char* name) { if (name == nullptr || std::string{name} == kDefaultAppName) { return App::Create(g_env, g_activity); } else { App* default_app = App::GetInstance(); FIREBASE_ASSERT_MESSAGE(default_app, "Cannot create a named app before the default app"); return App::Create(default_app->options(), name, g_env, g_activity); } } App* GetApp() { return GetApp(nullptr); } // Process events pending on the main thread. // Returns true when the app receives an event requesting exit. bool ProcessEvents(int msec) { android_poll_source* source = nullptr; int events; int looperId = ALooper_pollAll(msec, /*outFd=*/nullptr, &events, reinterpret_cast<void**>(&source)); if (looperId >= 0 && source) { source->process(g_app_state, source); } return g_destroy_requested | g_restarted; } FirestoreInternal* CreateTestFirestoreInternal(App* app) { return new FirestoreInternal(app); } void InitializeFirestore(Firestore*) { // No extra initialization necessary } } // namespace firestore } // namespace firebase extern "C" JNIEXPORT jboolean JNICALL NATIVE_FUNCTION_NAME(JNIEnv* env, jobject thiz, jobject activity, jstring filter) { if (env == nullptr || thiz == nullptr || activity == nullptr || filter == nullptr) { __android_log_print(ANDROID_LOG_INFO, __func__, "Invalid parameters."); return static_cast<jboolean>(false); } // Preparation work before run all tests. if (g_env == nullptr) { g_env = env; } if (g_activity == nullptr) { g_activity = activity; } // Anything that goes into std output will be gone. So we re-direct it into // android logcat. pipe(g_stdout_pipe_file); dup2(g_stdout_pipe_file[1], STDOUT_FILENO); if (pthread_create(&g_pipe_stdout_thread, nullptr, pipe_thread, g_stdout_pipe_file) == -1) { __android_log_print(ANDROID_LOG_INFO, __func__, "Failed to re-direct stdout to logcat"); } else { __android_log_print(ANDROID_LOG_INFO, __func__, "Dump stdout to logcat"); pthread_detach(g_pipe_stdout_thread); } pipe(g_stderr_pipe_file); dup2(g_stderr_pipe_file[1], STDERR_FILENO); if (pthread_create(&g_pipe_stderr_thread, nullptr, pipe_thread, g_stderr_pipe_file) == -1) { __android_log_print(ANDROID_LOG_INFO, __func__, "Failed to re-direct stderr to logcat"); } else { __android_log_print(ANDROID_LOG_INFO, __func__, "Dump stderr to logcat"); pthread_detach(g_pipe_stderr_thread); } // Required by gtest. Although this is a no-op. TODO(zxu): potentially pass // through the Java test flag and translate the JUnit test flag into an // equivalent gtest flag. int argc = 1; const char* argv[] = {STRINGIFY(NATIVE_FUNCTION_NAME)}; testing::InitGoogleTest(&argc, const_cast<char**>(argv)); testing::internal::GTestFlagSaver flag_saver; const char* filter_c_str = env->GetStringUTFChars(filter, /*isCopy=*/nullptr); testing::GTEST_FLAG(filter) = filter_c_str; env->ReleaseStringUTFChars(filter, filter_c_str); // Now run all tests. __android_log_print(ANDROID_LOG_INFO, __func__, "Start to run test %s", testing::GTEST_FLAG(filter).c_str()); auto unit_test = testing::UnitTest::GetInstance(); bool result = unit_test->Run() == 0; __android_log_print( ANDROID_LOG_INFO, __func__, "Tests finished.\n" " passed tests: %d\n" " skipped tests: %d\n" " failed tests: %d\n" " disabled tests: %d\n" " total tests: %d\n", unit_test->successful_test_count(), unit_test->skipped_test_count(), unit_test->failed_test_count(), unit_test->disabled_test_count(), unit_test->total_test_count()); return static_cast<jboolean>(result); } // Handle state changes from via native app glue. static void OnAppCmd(struct android_app* app, int32_t cmd) { g_destroy_requested |= cmd == APP_CMD_DESTROY; } // A dummy android_main() that flushes pending events and finishes the activity. // Modified from the Firebase Game's testapp. extern "C" void android_main(struct android_app* state) { // native_app_glue spawns a new thread, calling android_main() when the // activity onStart() or onRestart() methods are called. This code handles // the case where we're re-entering this method on a different thread by // signalling the existing thread to exit, waiting for it to complete before // reinitializing the application. if (g_started) { g_restarted = true; // Wait for the existing thread to exit. pthread_mutex_lock(&g_started_mutex); pthread_mutex_unlock(&g_started_mutex); } else { g_started_mutex = PTHREAD_MUTEX_INITIALIZER; } pthread_mutex_lock(&g_started_mutex); g_started = true; // Save native app glue state and setup a callback to track the state. g_destroy_requested = false; g_app_state = state; g_app_state->onAppCmd = OnAppCmd; // Wait until the user wants to quit the app. __android_log_print(ANDROID_LOG_INFO, __func__, "started. Waiting for events."); while (!firebase::firestore::ProcessEvents(1000)) { } // Finish the activity. __android_log_print(ANDROID_LOG_INFO, __func__, "quitting."); if (!g_restarted) ANativeActivity_finish(state->activity); g_app_state->activity->vm->DetachCurrentThread(); g_started = false; g_restarted = false; pthread_mutex_unlock(&g_started_mutex); } <file_sep>#include "firestore/src/ios/user_data_converter_ios.h" #include <set> #include <string> #include "firestore/src/ios/converter_ios.h" #include "firestore/src/ios/field_value_ios.h" #include "firestore/src/ios/hard_assert_ios.h" #include "firestore/src/ios/set_options_ios.h" #include "absl/memory/memory.h" #include "Firestore/core/src/firebase/firestore/core/user_data.h" #include "Firestore/core/src/firebase/firestore/model/field_mask.h" #include "Firestore/core/src/firebase/firestore/model/transform_operation.h" #include "Firestore/core/src/firebase/firestore/nanopb/byte_string.h" #include "Firestore/core/src/firebase/firestore/util/exception.h" namespace firebase { namespace firestore { namespace { using core::ParseAccumulator; using core::ParseContext; using core::ParsedSetData; using core::ParsedUpdateData; using core::UserDataSource; using model::ArrayTransform; using model::DatabaseId; using model::FieldMask; using model::NumericIncrementTransform; using model::ServerTimestampTransform; using model::TransformOperation; using nanopb::ByteString; using util::ThrowInvalidArgumentIos; using Type = FieldValue::Type; void ParseDelete(ParseContext&& context) { if (context.data_source() == UserDataSource::MergeSet) { // No transform to add for a delete, but we need to add it to our field mask // so it gets deleted. context.AddToFieldMask(*context.path()); return; } if (context.data_source() == UserDataSource::Update) { HARD_ASSERT_IOS( !context.path()->empty(), "FieldValue.Delete() at the top level should have already been " "handled."); // TODO(b/147444199): use string formatting. // ThrowInvalidArgument( // "FieldValue::Delete() can only appear at the top level of your " // "update data%s", // context.FieldDescription()); auto message = std::string( "FieldValue::Delete() can only appear at the top level of your " "update data") + context.FieldDescription(); ThrowInvalidArgumentIos(message.c_str()); } // We shouldn't encounter delete sentinels for queries or non-merge `Set` // calls. // TODO(b/147444199): use string formatting. // ThrowInvalidArgument( // "FieldValue::Delete() can only be used with Update() and Set() with " // "merge == true%s", // context.FieldDescription()); auto message = std::string( "FieldValue::Delete() can only be used with Update() and Set() with " "merge == true") + context.FieldDescription(); ThrowInvalidArgumentIos(message.c_str()); } void ParseServerTimestamp(ParseContext&& context) { context.AddToFieldTransforms(*context.path(), ServerTimestampTransform{}); } void ParseArrayTransform(Type type, const model::FieldValue::Array& elements, ParseContext&& context) { auto transform_type = [type] { switch (type) { case Type::kArrayUnion: return TransformOperation::Type::ArrayUnion; case Type::kArrayRemove: return TransformOperation::Type::ArrayRemove; default: { // TODO(b/147444199): use string formatting. // HARD_FAIL("Unexpected type '%s' given to ParseArrayTransform", type); auto message = std::string("Unexpected type '") + std::to_string(static_cast<int>(type)) + "' given to ParseArrayTransform"; HARD_FAIL_IOS(message.c_str()); } } }(); context.AddToFieldTransforms( *context.path(), ArrayTransform{transform_type, std::move(elements)}); } void ParseNumericIncrement(const FieldValue& value, ParseContext&& context) { model::FieldValue operand; switch (value.type()) { case Type::kIncrementDouble: operand = model::FieldValue::FromDouble(value.double_increment_value()); break; case Type::kIncrementInteger: operand = model::FieldValue::FromInteger(value.integer_increment_value()); break; default: HARD_FAIL_IOS("A non-increment value given to ParseNumericIncrement"); } context.AddToFieldTransforms(*context.path(), NumericIncrementTransform{std::move(operand)}); } FieldMask CreateFieldMask(const ParseAccumulator& accumulator, const std::vector<FieldPath>& field_paths) { std::set<model::FieldPath> validated; for (const FieldPath& public_path : field_paths) { const model::FieldPath& path = GetInternal(public_path); // Verify that all elements specified in the field mask are part of the // parsed context. if (!accumulator.Contains(path)) { // TODO(b/147444199): use string formatting. // ThrowInvalidArgument( // "Field '%s' is specified in your field mask but missing from your " // "input data.", // path.CanonicalString()); auto message = std::string("Field '") + path.CanonicalString() + "' is specified in your field mask but missing from your input data."; ThrowInvalidArgumentIos(message.c_str()); } validated.insert(path); } return FieldMask{std::move(validated)}; } } // namespace // Public entry points ParsedSetData UserDataConverter::ParseSetData(const MapFieldValue& data, const SetOptions& options) const { SetOptionsInternal internal_options{options}; switch (internal_options.type()) { case SetOptions::Type::kOverwrite: return ParseSetData(data); case SetOptions::Type::kMergeAll: return ParseMergeData(data); case SetOptions::Type::kMergeSpecific: return ParseMergeData(data, internal_options.field_mask()); } UNREACHABLE(); } ParsedUpdateData UserDataConverter::ParseUpdateData( const MapFieldValue& input) const { UpdateDataInput converted_input; converted_input.reserve(input.size()); for (const auto& kv : input) { converted_input.emplace_back( model::FieldPath::FromDotSeparatedString(kv.first), &kv.second); } return ParseUpdateData(converted_input); } ParsedUpdateData UserDataConverter::ParseUpdateData( const MapFieldPathValue& input) const { UpdateDataInput converted_input; converted_input.reserve(input.size()); for (const auto& kv : input) { converted_input.emplace_back(GetInternal(kv.first), &kv.second); } return ParseUpdateData(converted_input); } // Implementation ParsedSetData UserDataConverter::ParseSetData( const MapFieldValue& input) const { ParseAccumulator accumulator{UserDataSource::Set}; auto data = ParseMap(input, accumulator.RootContext()); return std::move(accumulator).SetData(std::move(data)); } ParsedSetData UserDataConverter::ParseMergeData( const MapFieldValue& input, const absl::optional<std::vector<FieldPath>>& maybe_field_mask) const { ParseAccumulator accumulator{UserDataSource::MergeSet}; auto data = ParseMap(input, accumulator.RootContext()); if (!maybe_field_mask) { return std::move(accumulator).MergeData(std::move(data)); } return std::move(accumulator) .MergeData(std::move(data), CreateFieldMask(accumulator, maybe_field_mask.value())); } model::FieldValue UserDataConverter::ParseQueryValue(const FieldValue& input, bool allow_arrays) const { ParseAccumulator accumulator{allow_arrays ? UserDataSource::ArrayArgument : UserDataSource::Argument}; absl::optional<model::FieldValue> parsed = ParseData(input, accumulator.RootContext()); HARD_ASSERT_IOS(parsed, "Parsed data should not be nullopt."); HARD_ASSERT_IOS(accumulator.field_transforms().empty(), "Field transforms should have been disallowed."); return parsed.value(); } absl::optional<model::FieldValue> UserDataConverter::ParseData( const FieldValue& value, ParseContext&& context) const { auto maybe_add_to_field_mask = [&] { if (context.path()) { context.AddToFieldMask(*context.path()); } }; switch (value.type()) { case Type::kArray: maybe_add_to_field_mask(); return model::FieldValue::FromArray( ParseArray(value.array_value(), std::move(context))); case Type::kMap: return ParseMap(value.map_value(), std::move(context)).AsFieldValue(); case Type::kDelete: case Type::kServerTimestamp: case Type::kArrayUnion: case Type::kArrayRemove: case Type::kIncrementDouble: case Type::kIncrementInteger: ParseSentinel(value, std::move(context)); return absl::nullopt; default: maybe_add_to_field_mask(); return ParseScalar(value, std::move(context)); } } model::FieldValue::Array UserDataConverter::ParseArray( const std::vector<FieldValue>& input, ParseContext&& context) const { // In the case of IN queries, the parsed data is an array (representing the // set of values to be included for the IN query) that may directly contain // additional arrays (each representing an individual field value), so we // disable this validation. if (context.array_element() && context.data_source() != core::UserDataSource::ArrayArgument) { ThrowInvalidArgumentIos("Nested arrays are not supported"); } model::FieldValue::Array result; for (size_t i = 0; i != input.size(); ++i) { absl::optional<model::FieldValue> parsed = ParseData(input[i], context.ChildContext(i)); if (!parsed) { parsed = model::FieldValue::Null(); } result.push_back(std::move(parsed).value()); } return result; } model::ObjectValue UserDataConverter::ParseMap(const MapFieldValue& input, ParseContext&& context) const { if (input.empty()) { const model::FieldPath* path = context.path(); if (path && !path->empty()) { context.AddToFieldMask(*path); } return model::ObjectValue{}; } model::FieldValue::Map result; for (const auto& kv : input) { const std::string& key = kv.first; const FieldValue& value = kv.second; absl::optional<model::FieldValue> parsed = ParseData(value, context.ChildContext(key)); if (parsed) { result = result.insert(key, std::move(parsed).value()); } } return model::ObjectValue::FromMap(std::move(result)); } void UserDataConverter::ParseSentinel(const FieldValue& value, ParseContext&& context) const { // Sentinels are only supported with writes, and not within arrays. if (!context.write()) { // TODO(b/147444199): use string formatting. // ThrowInvalidArgument("%s can only be used with Update() and Set()%s", // Describe(value.type()), context.FieldDescription()); auto message = Describe(value.type()) + " can only be used with Update() and Set()" + context.FieldDescription(); ThrowInvalidArgumentIos(message.c_str()); } if (!context.path()) { // TODO(b/147444199): use string formatting. // ThrowInvalidArgument("%s is not currently supported inside arrays", // Describe(value.type())); auto message = Describe(value.type()) + " is not currently supported inside arrays"; ThrowInvalidArgumentIos(message.c_str()); } switch (value.type()) { case Type::kDelete: ParseDelete(std::move(context)); break; case Type::kServerTimestamp: ParseServerTimestamp(std::move(context)); break; case Type::kArrayUnion: // Fallthrough case Type::kArrayRemove: ParseArrayTransform(value.type(), ParseArrayTransformElements(value), std::move(context)); break; case Type::kIncrementDouble: case Type::kIncrementInteger: ParseNumericIncrement(value, std::move(context)); break; default: // TODO(b/147444199): use string formatting. // HARD_FAIL("Unknown FieldValue type: '%s'", Describe(value.type())); auto message = std::string("Unknown FieldValue type: '") + Describe(value.type()) + "'"; HARD_FAIL_IOS(message.c_str()); } } model::FieldValue UserDataConverter::ParseScalar(const FieldValue& value, ParseContext&& context) const { switch (value.type()) { case Type::kNull: return model::FieldValue::Null(); case Type::kBoolean: return model::FieldValue::FromBoolean(value.boolean_value()); case Type::kInteger: return model::FieldValue::FromInteger(value.integer_value()); case Type::kDouble: return model::FieldValue::FromDouble(value.double_value()); case Type::kTimestamp: { // Truncate to microsecond precision immediately. Timestamp truncated{value.timestamp_value().seconds(), value.timestamp_value().nanoseconds() / 1000 * 1000}; return model::FieldValue::FromTimestamp(truncated); } case Type::kString: return model::FieldValue::FromString(value.string_value()); case Type::kBlob: { ByteString blob{value.blob_value(), value.blob_size()}; return model::FieldValue::FromBlob(std::move(blob)); } case Type::kReference: { DocumentReference reference = value.reference_value(); const DatabaseId& other = GetInternal(reference.firestore())->database_id(); if (other != *database_id_) { // TODO(b/147444199): use string formatting. // ThrowInvalidArgument( // "DocumentReference is for database %s/%s but should be for " // "database %s/%s%s", // other.project_id(), other.database_id(), // database_id_->project_id(), database_id_->database_id(), // context.FieldDescription()); auto actual_db = other.project_id() + "/" + other.database_id(); auto expected_db = database_id_->project_id() + "/" + database_id_->database_id(); auto message = std::string("DocumentReference is for database ") + actual_db + " but should be for database " + expected_db + context.FieldDescription(); ThrowInvalidArgumentIos(message.c_str()); } const model::DocumentKey& key = GetInternal(&reference)->key(); return model::FieldValue::FromReference(*database_id_, key); } case Type::kGeoPoint: return model::FieldValue::FromGeoPoint(value.geo_point_value()); default: HARD_FAIL_IOS("A non-scalar field value given to ParseScalar"); } } model::FieldValue::Array UserDataConverter::ParseArrayTransformElements( const FieldValue& value) const { std::vector<FieldValue> elements = GetInternal(&value)->array_transform_value(); model::FieldValue::Array result; ParseAccumulator accumulator{UserDataSource::Argument}; for (size_t i = 0; i != elements.size(); ++i) { const FieldValue& element = elements[i]; // Although array transforms are used with writes, the actual elements being // unioned or removed are not considered writes since they cannot contain // any FieldValue sentinels, etc. ParseContext context = accumulator.RootContext(); absl::optional<model::FieldValue> parsed_element = ParseData(element, context.ChildContext(i)); // TODO(b/147444199): use string formatting. // HARD_ASSERT(parsed_element && accumulator.field_transforms().empty(), // "Failed to properly parse array transform element: %s", // Describe(element.type())); if (!parsed_element || !accumulator.field_transforms().empty()) { auto message = std::string("Failed to properly parse array transform element: ") + Describe(element.type()); HARD_FAIL_IOS(message.c_str()); } result.push_back(std::move(parsed_element).value()); } return result; } ParsedUpdateData UserDataConverter::ParseUpdateData( const UpdateDataInput& input) const { ParseAccumulator accumulator{UserDataSource::Update}; ParseContext context = accumulator.RootContext(); model::ObjectValue update_data; for (const auto& kv : input) { const model::FieldPath& path = kv.first; const FieldValue& value = *kv.second; if (value.type() == Type::kDelete) { // Add it to the field mask, but don't add anything to update_data. context.AddToFieldMask(path); break; } absl::optional<model::FieldValue> parsed = ParseData(value, context.ChildContext(path)); if (parsed) { context.AddToFieldMask(path); update_data = update_data.Set(path, std::move(parsed).value()); } } return std::move(accumulator).UpdateData(std::move(update_data)); } } // namespace firestore } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_COMMON_FUTURES_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_COMMON_FUTURES_H_ #include "app/src/include/firebase/future.h" #include "app/src/reference_counted_future_impl.h" #include "firebase/firestore/firestore_errors.h" namespace firebase { namespace firestore { namespace internal { /** * Do not use this directly. Originally, this was inlined as a lambda. But that * breaks on older compilers, i.e. at least gcc-4.8.5. */ template <typename T> Future<T> CreateFailedFuture( ReferenceCountedFutureImpl* ref_counted_future_impl) { SafeFutureHandle<T> handle = ref_counted_future_impl->SafeAlloc<T>(); ref_counted_future_impl->Complete( handle, Error::FailedPrecondition, "This instance is in an invalid state. This could either because the " "underlying Firestore instance has been destructed or because you're " "running on an unsupported platform. Currently the Firestore C++/Unity " "SDK only supports iOS / Android devices."); return Future<T>(ref_counted_future_impl, handle.get()); } } // namespace internal /** * Returns a failed future suitable for returning from a stub or "invalid" * instance. * * Note that without proper Desktop support, we use firsetore_stub.cc which * uses FailedFuture() for its own methods but constructs "invalid" instances * of DocumentReference, etc. which also use FailedFuture(). So the wrapped * error must be generic enough to cover both unimplemented desktop support as * well as normal "invalid" instances (i.e. the underlying Firestore instance * has been destructed). */ template <typename T> Future<T> FailedFuture() { static ReferenceCountedFutureImpl ref_counted_future_impl( /*last_result_count=*/0); static Future<T> future = internal::CreateFailedFuture<T>(&ref_counted_future_impl); return future; } } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_COMMON_FUTURES_H_ <file_sep>// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef FIREBASE_REMOTE_CONFIG_CLIENT_CPP_SRC_DESKTOP_REST_H_ #define FIREBASE_REMOTE_CONFIG_CLIENT_CPP_SRC_DESKTOP_REST_H_ #include <cstdint> #include "firebase/app.h" #include "app/src/semaphore.h" #ifndef REST_STUB_IMPL // These pull in unnecessary deps for the stub #include "app/rest/request_binary_gzip.h" #include "app/rest/response_binary.h" #endif // REST_STUB_IMPL #include "remote_config/src/desktop/config_data.h" #ifdef FIREBASE_TESTING #include "gtest/gtest.h" #endif // FIREBASE_TESTING namespace firebase { namespace remote_config { namespace internal { // These are used in tests to build a regular protobuf for comparison. extern const int SDK_MAJOR_VERSION; extern const int SDK_MINOR_VERSION; extern const int SDK_PATCH_VERSION; // These are structures used to build a request. struct ConfigFetchRequest; struct PackageData; #ifdef DEBUG_SERVER const char* const kServerURL = "https://jmt17.google.com/config"; #else const char* const kServerURL = "https://cloudconfig.googleapis.com/config"; #endif const char* const kHTTPMethodPost = "POST"; const char* const kContentTypeHeaderName = "Content-Type"; const char* const kContentTypeValue = "application/x-protobuffer"; // Set this key with value `1` if settings[kConfigSettingDeveloperMode] == `1` const char* const kDeveloperModeKey = "_rcn_developer"; const int kHTTPStatusOk = 200; class RemoteConfigREST { public: #ifdef FIREBASE_TESTING friend class RemoteConfigRESTTest; FRIEND_TEST(RemoteConfigRESTTest, SetupProto); FRIEND_TEST(RemoteConfigRESTTest, SetupRESTRequest); FRIEND_TEST(RemoteConfigRESTTest, Fetch); FRIEND_TEST(RemoteConfigRESTTest, ParseRestResponseProtoFailure); FRIEND_TEST(RemoteConfigRESTTest, ParseRestResponseSuccess); #endif // FIREBASE_TESTING RemoteConfigREST(const firebase::AppOptions& app_options, const LayeredConfigs& configs, uint64_t cache_expiration_in_seconds); ~RemoteConfigREST(); // 1. Attempt to Fetch Instance Id and token. App is required to get an // instance of InstanceIdDesktopImpl. // 2. Setup REST request; // 3. Make REST request; // 4. Parse REST response. void Fetch(const App& app); // After Fetch() will return updated fetched holder. Otherwise will return not // updated fetched holder. const NamespacedConfigData& fetched() const { return configs_.fetched; } // After Fetch() will return updated metadata. Otherwise will return not // updated metadata. const RemoteConfigMetadata& metadata() const { return configs_.metadata; } private: // Attempt to get Instance Id and token from app synchronously. This will // block the current thread and wait until the futures are complete. void TryGetInstanceIdAndToken(const App& app); // Setup all values to make REST request. Call `SetupProtoRequest` to setup // post fields. void SetupRestRequest(); // Setup protobuf ConfigFetchRequest object for REST request post fields. Call // `GetPackageData` to setup PackageData for ConfigFetchRequest. ConfigFetchRequest GetFetchRequestData(); // Setup PackageData for ConfigFetchRequest. void GetPackageData(PackageData* package_data); // Parse REST response. Check response status and body. void ParseRestResponse(); // Parse REST response body `proto_str` to ConfigFetchResponse protobuf // object. Update `configs_` variable based on ConfigFetchResponse. void ParseProtoResponse(const std::string& proto_str); // Return timestamp in milliseconds. uint64_t MillisecondsSinceEpoch(); // Update metadata after successful fetching. void FetchSuccess(LastFetchStatus status); // Update metadata after failed fetching. void FetchFailure(FetchFailureReason reason); // app fields: std::string app_package_name_; std::string app_gmp_project_id_; LayeredConfigs configs_; // cache expiration uint64_t cache_expiration_in_seconds_; // Instance Id data std::string app_instance_id_; std::string app_instance_id_token_; // The semaphore to block the thread and wait for. Semaphore fetch_future_sem_; #ifndef REST_STUB_IMPL // HTTP request/response firebase::rest::RequestBinaryGzip rest_request_; firebase::rest::ResponseBinary rest_response_; #endif // REST_STUB_IMPL }; } // namespace internal } // namespace remote_config } // namespace firebase #endif // FIREBASE_REMOTE_CONFIG_CLIENT_CPP_SRC_DESKTOP_REST_H_ <file_sep>#include "firestore/src/android/listener_registration_android.h" #include "app/src/assert.h" #include "app/src/util_android.h" #include "firestore/src/include/firebase/firestore/listener_registration.h" namespace firebase { namespace firestore { #define LISTENER_REGISTRATION_METHODS(X) X(Remove, "remove", "()V") METHOD_LOOKUP_DECLARATION(listener_registration, LISTENER_REGISTRATION_METHODS) METHOD_LOOKUP_DEFINITION(listener_registration, PROGUARD_KEEP_CLASS "com/google/firebase/firestore/ListenerRegistration", LISTENER_REGISTRATION_METHODS) ListenerRegistrationInternal::ListenerRegistrationInternal( FirestoreInternal* firestore, EventListener<DocumentSnapshot>* event_listener, bool owning_event_listener, jobject listener_registration) : firestore_(firestore), listener_registration_( firestore->app()->GetJNIEnv()->NewGlobalRef(listener_registration)), document_event_listener_(event_listener), owning_event_listener_(owning_event_listener) { FIREBASE_ASSERT(firestore != nullptr); FIREBASE_ASSERT(event_listener != nullptr); FIREBASE_ASSERT(listener_registration != nullptr); firestore->RegisterListenerRegistration(this); } ListenerRegistrationInternal::ListenerRegistrationInternal( FirestoreInternal* firestore, EventListener<QuerySnapshot>* event_listener, bool owning_event_listener, jobject listener_registration) : firestore_(firestore), listener_registration_( firestore->app()->GetJNIEnv()->NewGlobalRef(listener_registration)), query_event_listener_(event_listener), owning_event_listener_(owning_event_listener) { FIREBASE_ASSERT(firestore != nullptr); FIREBASE_ASSERT(event_listener != nullptr); FIREBASE_ASSERT(listener_registration != nullptr); firestore->RegisterListenerRegistration(this); } ListenerRegistrationInternal::ListenerRegistrationInternal( FirestoreInternal* firestore, EventListener<void>* event_listener, bool owning_event_listener, jobject listener_registration) : firestore_(firestore), listener_registration_( firestore->app()->GetJNIEnv()->NewGlobalRef(listener_registration)), void_event_listener_(event_listener), owning_event_listener_(owning_event_listener) { FIREBASE_ASSERT(firestore != nullptr); FIREBASE_ASSERT(event_listener != nullptr); FIREBASE_ASSERT(listener_registration != nullptr); firestore->RegisterListenerRegistration(this); } // Destruction only happens when FirestoreInternal de-allocate them. // FirestoreInternal will hold the lock and unregister all of them. So we do not // call UnregisterListenerRegistration explicitly here. ListenerRegistrationInternal::~ListenerRegistrationInternal() { if (listener_registration_ == nullptr) { return; } // Remove listener and release java ListenerRegistration object. JNIEnv* env = firestore_->app()->GetJNIEnv(); env->CallVoidMethod( listener_registration_, listener_registration::GetMethodId(listener_registration::kRemove)); env->DeleteGlobalRef(listener_registration_); util::CheckAndClearJniExceptions(env); listener_registration_ = nullptr; // de-allocate owning EventListener object. if (owning_event_listener_) { delete document_event_listener_; delete query_event_listener_; delete void_event_listener_; } } /* static */ bool ListenerRegistrationInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = listener_registration::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void ListenerRegistrationInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); listener_registration::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>#include "firestore/src/android/timestamp_android.h" #include <stdint.h> #include "app/src/util_android.h" #include "firestore/src/android/util_android.h" namespace firebase { namespace firestore { // clang-format off #define TIMESTAMP_METHODS(X) \ X(Constructor, "<init>", "(JI)V", util::kMethodTypeInstance), \ X(GetSeconds, "getSeconds", "()J"), \ X(GetNanoseconds, "getNanoseconds", "()I") // clang-format on METHOD_LOOKUP_DECLARATION(timestamp, TIMESTAMP_METHODS) METHOD_LOOKUP_DEFINITION(timestamp, PROGUARD_KEEP_CLASS "com/google/firebase/Timestamp", TIMESTAMP_METHODS) /* static */ jobject TimestampInternal::TimestampToJavaTimestamp( JNIEnv* env, const Timestamp& timestamp) { jobject result = env->NewObject( timestamp::GetClass(), timestamp::GetMethodId(timestamp::kConstructor), static_cast<jlong>(timestamp.seconds()), static_cast<jint>(timestamp.nanoseconds())); CheckAndClearJniExceptions(env); return result; } /* static */ Timestamp TimestampInternal::JavaTimestampToTimestamp(JNIEnv* env, jobject obj) { jlong seconds = env->CallLongMethod(obj, timestamp::GetMethodId(timestamp::kGetSeconds)); jint nanoseconds = env->CallIntMethod( obj, timestamp::GetMethodId(timestamp::kGetNanoseconds)); CheckAndClearJniExceptions(env); return Timestamp{static_cast<int64_t>(seconds), static_cast<int32_t>(nanoseconds)}; } /* static */ jclass TimestampInternal::GetClass() { return timestamp::GetClass(); } /* static */ bool TimestampInternal::Initialize(App* app) { JNIEnv* env = app->GetJNIEnv(); jobject activity = app->activity(); bool result = timestamp::CacheMethodIds(env, activity); util::CheckAndClearJniExceptions(env); return result; } /* static */ void TimestampInternal::Terminate(App* app) { JNIEnv* env = app->GetJNIEnv(); timestamp::ReleaseClass(env); util::CheckAndClearJniExceptions(env); } } // namespace firestore } // namespace firebase <file_sep>// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <cstdint> #include <string> #include "instance_id/src/include/firebase/instance_id.h" #include "instance_id/src/instance_id_internal.h" namespace firebase { namespace instance_id { using internal::InstanceIdInternal; int64_t InstanceId::creation_time() const { return 0; } Future<std::string> InstanceId::GetId() const { if (!instance_id_internal_) return Future<std::string>(); const auto future_handle = instance_id_internal_->FutureAlloc<std::string>( InstanceIdInternal::kApiFunctionGetId); instance_id_internal_->future_api().CompleteWithResult( future_handle, kErrorNone, "", std::string("FakeId")); return GetIdLastResult(); } Future<void> InstanceId::DeleteId() { if (!instance_id_internal_) return Future<void>(); const auto future_handle = instance_id_internal_->FutureAlloc<void>( InstanceIdInternal::kApiFunctionDeleteId); instance_id_internal_->future_api().Complete(future_handle, kErrorNone, ""); return DeleteIdLastResult(); } Future<std::string> InstanceId::GetToken(const char* entity, const char* scope) { if (!instance_id_internal_) return Future<std::string>(); const auto future_handle = instance_id_internal_->FutureAlloc<std::string>( InstanceIdInternal::kApiFunctionGetToken); instance_id_internal_->future_api().CompleteWithResult( future_handle, kErrorNone, "", std::string("FakeToken")); return GetTokenLastResult(); } Future<void> InstanceId::DeleteToken(const char* entity, const char* scope) { if (!instance_id_internal_) return Future<void>(); const auto future_handle = instance_id_internal_->FutureAlloc<void>( InstanceIdInternal::kApiFunctionDeleteToken); instance_id_internal_->future_api().Complete(future_handle, kErrorNone, ""); return DeleteTokenLastResult(); } InstanceId* InstanceId::GetInstanceId(App* app, InitResult* init_result_out) { if (init_result_out) *init_result_out = kInitResultSuccess; auto instance_id = InstanceIdInternal::FindInstanceIdByApp(app); if (instance_id) return instance_id; return new InstanceId(app, new InstanceIdInternal()); } } // namespace instance_id } // namespace firebase <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_TRANSACTION_ANDROID_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_TRANSACTION_ANDROID_H_ #include <string> #include "app/memory/shared_ptr.h" #include "app/meta/move.h" #include "app/src/embedded_file.h" #include "firestore/src/android/wrapper_future.h" #include "firestore/src/include/firebase/firestore/document_reference.h" #include "firestore/src/include/firebase/firestore/map_field_value.h" #include "firestore/src/include/firebase/firestore/transaction.h" namespace firebase { namespace firestore { class TransactionInternal : public Wrapper { public: using ApiType = Transaction; TransactionInternal(FirestoreInternal* firestore, jobject obj) : Wrapper(firestore, obj), first_exception_{new jthrowable{nullptr}} {} TransactionInternal(const TransactionInternal& rhs) : Wrapper(rhs), first_exception_(rhs.first_exception_) {} TransactionInternal(TransactionInternal&& rhs) : Wrapper(firebase::Move(rhs)), first_exception_(rhs.first_exception_) {} void Set(const DocumentReference& document, const MapFieldValue& data, const SetOptions& options); void Update(const DocumentReference& document, const MapFieldValue& data); void Update(const DocumentReference& document, const MapFieldPathValue& data); void Delete(const DocumentReference& document); DocumentSnapshot Get(const DocumentReference& document, Error* error_code, std::string* error_message); static jobject ToJavaObject(JNIEnv* env, FirestoreInternal* firestore, TransactionFunction* function); static jobject TransactionFunctionNativeApply(JNIEnv* env, jclass clazz, jlong firestore_ptr, jlong transaction_function_ptr, jobject transaction); private: // If this is the first exception, then store it. Otherwise, preserve the // current exception. Passing nullptr has no effect. void PreserveException(jthrowable exception); // Clear the global reference of the first exception, if any. The SharedPtr // does not support custom deleters and thus we must call this explicitly. // The workflow of RunTransaction allows us to do so. void ClearException(); // A helper function to replace util::CheckAndClearJniExceptions(env). It will // check and clear all exceptions just as what the one under util is doing. In // addition, it also preserves the first ever exception during a Transaction. // We do not preserve each and every exception. Only the first one matters and // more than likely the subsequent exception is caused by the first one. bool CheckAndClearJniExceptions(); friend class FirestoreInternal; static bool Initialize(App* app); static bool InitializeEmbeddedClasses( App* app, const std::vector<internal::EmbeddedFile>* embedded_files); static void Terminate(App* app); // The first exception that occurred. Because exceptions must be cleared // before calling other JNI methods, we cannot rely on the Java exception // mechanism to properly handle native calls via JNI. The first exception is // shared by a transaction and its copies. User is allowed to make copy and // call transaction operation on the copy. SharedPtr<jthrowable> first_exception_; }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_TRANSACTION_ANDROID_H_ <file_sep>#ifndef FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_WRAPPER_H_ #define FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_WRAPPER_H_ #include <jni.h> #include <vector> #include "app/src/util_android.h" #include "firestore/src/android/firestore_android.h" #include "firestore/src/android/util_android.h" #include "firestore/src/include/firebase/firestore/field_path.h" #include "firestore/src/include/firebase/firestore/field_value.h" #include "firestore/src/include/firebase/firestore/map_field_value.h" namespace firebase { namespace firestore { class FieldValueInternal; class FirestoreInternal; // This is the generalized wrapper base class which contains a FirestoreInternal // client instance as well as a jobject, around which this wrapper is. class Wrapper { public: // A global reference will be created from obj. The caller is responsible for // cleaning up any local references to obj after the constructor returns. Wrapper(FirestoreInternal* firestore, jobject obj); // Construct a new Java object and wrap around it. clazz is supposed to be the // java class of the type of the new Java object and method_id is supposed to // be the method id of one of the constructor of the new Java object. The // parameters to be used in constructing the new Java object have to be passed // through the variadic arguments in JNI-typed format such as jobject or jint. // If the constructor accepts no parameter, then leave the variadic arguments // empty. Wrapper(jclass clazz, jmethodID method_id, ...); Wrapper(const Wrapper& wrapper); Wrapper(Wrapper&& wrapper) noexcept; virtual ~Wrapper(); // So far, there is no use of assignment. So we do not bother to define our // own and delete the default one, which does not copy jobject properly. Wrapper& operator=(const Wrapper& wrapper) = delete; Wrapper& operator=(Wrapper&& wrapper) = delete; FirestoreInternal* firestore_internal() { return firestore_; } jobject java_object() { return obj_; } // Tests the equality of the wrapped Java Object. bool EqualsJavaObject(const Wrapper& other) const; protected: enum class AllowNullObject { Yes }; // Default constructor. Subclass is expected to set the obj_ a meaningful // value. Wrapper(); // Similar to Wrapper(FirestoreInternal*, jobject) but allowing obj be Null // Java object a.k.a. nullptr. Wrapper(FirestoreInternal* firestore, jobject obj, AllowNullObject); // Similar to a copy constructor, but can handle the case where `rhs` is null. explicit Wrapper(Wrapper* rhs); // Converts a java list of java type e.g. java.util.List<FirestoreJavaType> to // a C++ vector of equivalent type e.g. std::vector<FirestoreType>. template <typename FirestoreType, typename FirestoreTypeInternal> static void JavaListToStdVector(FirestoreInternal* firestore, jobject from, std::vector<FirestoreType>* to) { JNIEnv* env = firestore->app()->GetJNIEnv(); int size = env->CallIntMethod(from, util::list::GetMethodId(util::list::kSize)); CheckAndClearJniExceptions(env); to->clear(); to->reserve(size); for (int i = 0; i < size; ++i) { jobject element = env->CallObjectMethod( from, util::list::GetMethodId(util::list::kGet), i); CheckAndClearJniExceptions(env); // Cannot call with emplace_back since the constructor is protected. to->push_back( FirestoreType{new FirestoreTypeInternal{firestore, element}}); env->DeleteLocalRef(element); } } // Converts a MapFieldValue to a java Map object that maps String to Object. // The caller is responsible for freeing the returned jobject via // JNIEnv::DeleteLocalRef(). static jobject MapFieldValueToJavaMap(FirestoreInternal* firestore, const MapFieldValue& data); // Makes a variadic parameters from C++ MapFieldPathValue iterators up to the // given size. The caller is responsible for freeing the returned jobject via // JNIENV::DeleteLocalRef(). This helper takes iterators instead of // MapFieldPathValue directly because the Android native client API may // require passing the first pair explicit and thus the variadic starting from // the second pair. static jobjectArray MapFieldPathValueToJavaArray( FirestoreInternal* firestore, MapFieldPathValue::const_iterator begin, MapFieldPathValue::const_iterator end); FirestoreInternal* firestore_ = nullptr; // not owning jobject obj_ = nullptr; private: friend class FirestoreInternal; static bool Initialize(App* app); static void Terminate(App* app); }; } // namespace firestore } // namespace firebase #endif // FIREBASE_FIRESTORE_CLIENT_CPP_SRC_ANDROID_WRAPPER_H_ <file_sep>#include "firestore/src/include/firebase/firestore/write_batch.h" #include <utility> #include "app/src/assert.h" #include "app/src/include/firebase/future.h" #include "firestore/src/common/cleanup.h" #include "firestore/src/common/futures.h" #include "firestore/src/include/firebase/firestore/document_reference.h" #if defined(__ANDROID__) #include "firestore/src/android/write_batch_android.h" #elif defined(FIRESTORE_STUB_BUILD) #include "firestore/src/stub/write_batch_stub.h" #else #include "firestore/src/ios/write_batch_ios.h" #endif // defined(__ANDROID__) namespace firebase { namespace firestore { using CleanupFnWriteBatch = CleanupFn<WriteBatch, WriteBatchInternal>; WriteBatch::WriteBatch() {} WriteBatch::WriteBatch(const WriteBatch& value) { if (value.internal_) { internal_ = new WriteBatchInternal(*value.internal_); } CleanupFnWriteBatch::Register(this, internal_); } WriteBatch::WriteBatch(WriteBatch&& value) { CleanupFnWriteBatch::Unregister(&value, value.internal_); std::swap(internal_, value.internal_); CleanupFnWriteBatch::Register(this, internal_); } WriteBatch::WriteBatch(WriteBatchInternal* internal) : internal_(internal) { FIREBASE_ASSERT(internal != nullptr); CleanupFnWriteBatch::Register(this, internal_); } WriteBatch::~WriteBatch() { CleanupFnWriteBatch::Unregister(this, internal_); delete internal_; internal_ = nullptr; } WriteBatch& WriteBatch::operator=(const WriteBatch& value) { if (this == &value) { return *this; } CleanupFnWriteBatch::Unregister(this, internal_); delete internal_; if (value.internal_) { internal_ = new WriteBatchInternal(*value.internal_); } else { internal_ = nullptr; } CleanupFnWriteBatch::Register(this, internal_); return *this; } WriteBatch& WriteBatch::operator=(WriteBatch&& value) { if (this == &value) { return *this; } CleanupFnWriteBatch::Unregister(&value, value.internal_); CleanupFnWriteBatch::Unregister(this, internal_); delete internal_; internal_ = value.internal_; value.internal_ = nullptr; CleanupFnWriteBatch::Register(this, internal_); return *this; } WriteBatch& WriteBatch::Set(const DocumentReference& document, const MapFieldValue& data, const SetOptions& options) { if (!internal_) return *this; internal_->Set(document, data, options); return *this; } WriteBatch& WriteBatch::Update(const DocumentReference& document, const MapFieldValue& data) { if (!internal_) return *this; internal_->Update(document, data); return *this; } WriteBatch& WriteBatch::Update(const DocumentReference& document, const MapFieldPathValue& data) { if (!internal_) return *this; internal_->Update(document, data); return *this; } WriteBatch& WriteBatch::Delete(const DocumentReference& document) { if (!internal_) return *this; internal_->Delete(document); return *this; } Future<void> WriteBatch::Commit() { if (!internal_) return FailedFuture<void>(); return internal_->Commit(); } Future<void> WriteBatch::CommitLastResult() const { if (!internal_) return FailedFuture<void>(); return internal_->CommitLastResult(); } } // namespace firestore } // namespace firebase
4ce0e532a8af27e99e554aa135fd0cc5e74a7aea
[ "CMake", "Ruby", "Java", "Python", "C", "C++", "Shell" ]
143
C++
NetsoftHoldings/firebase-cpp-sdk
356c63bddde5ed76483cbfc5f3ff5b228c5cbe1f
40c0e8195832e685ddd78aa496638a5f5b14b913
refs/heads/master
<repo_name>yoshipaulbrophy/google-api-cpp-client<file_sep>/service_apis/youtube/google/youtube_api/channel_settings.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_CHANNEL_SETTINGS_H_ #define GOOGLE_YOUTUBE_API_CHANNEL_SETTINGS_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Branding properties for the channel view. * * @ingroup DataObject */ class ChannelSettings : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static ChannelSettings* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelSettings(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelSettings(Json::Value* storage); /** * Standard destructor. */ virtual ~ChannelSettings(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::ChannelSettings</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::ChannelSettings"); } /** * Determine if the '<code>country</code>' attribute was set. * * @return true if the '<code>country</code>' attribute was set. */ bool has_country() const { return Storage().isMember("country"); } /** * Clears the '<code>country</code>' attribute. */ void clear_country() { MutableStorage()->removeMember("country"); } /** * Get the value of the '<code>country</code>' attribute. */ const StringPiece get_country() const { const Json::Value& v = Storage("country"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>country</code>' attribute. * * The country of the channel. * * @param[in] value The new value. */ void set_country(const StringPiece& value) { *MutableStorage("country") = value.data(); } /** * Determine if the '<code>defaultLanguage</code>' attribute was set. * * @return true if the '<code>defaultLanguage</code>' attribute was set. */ bool has_default_language() const { return Storage().isMember("defaultLanguage"); } /** * Clears the '<code>defaultLanguage</code>' attribute. */ void clear_default_language() { MutableStorage()->removeMember("defaultLanguage"); } /** * Get the value of the '<code>defaultLanguage</code>' attribute. */ const StringPiece get_default_language() const { const Json::Value& v = Storage("defaultLanguage"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>defaultLanguage</code>' attribute. * @param[in] value The new value. */ void set_default_language(const StringPiece& value) { *MutableStorage("defaultLanguage") = value.data(); } /** * Determine if the '<code>defaultTab</code>' attribute was set. * * @return true if the '<code>defaultTab</code>' attribute was set. */ bool has_default_tab() const { return Storage().isMember("defaultTab"); } /** * Clears the '<code>defaultTab</code>' attribute. */ void clear_default_tab() { MutableStorage()->removeMember("defaultTab"); } /** * Get the value of the '<code>defaultTab</code>' attribute. */ const StringPiece get_default_tab() const { const Json::Value& v = Storage("defaultTab"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>defaultTab</code>' attribute. * * Which content tab users should see when viewing the channel. * * @param[in] value The new value. */ void set_default_tab(const StringPiece& value) { *MutableStorage("defaultTab") = value.data(); } /** * Determine if the '<code>description</code>' attribute was set. * * @return true if the '<code>description</code>' attribute was set. */ bool has_description() const { return Storage().isMember("description"); } /** * Clears the '<code>description</code>' attribute. */ void clear_description() { MutableStorage()->removeMember("description"); } /** * Get the value of the '<code>description</code>' attribute. */ const StringPiece get_description() const { const Json::Value& v = Storage("description"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>description</code>' attribute. * * Specifies the channel description. * * @param[in] value The new value. */ void set_description(const StringPiece& value) { *MutableStorage("description") = value.data(); } /** * Determine if the '<code>featuredChannelsTitle</code>' attribute was set. * * @return true if the '<code>featuredChannelsTitle</code>' attribute was set. */ bool has_featured_channels_title() const { return Storage().isMember("featuredChannelsTitle"); } /** * Clears the '<code>featuredChannelsTitle</code>' attribute. */ void clear_featured_channels_title() { MutableStorage()->removeMember("featuredChannelsTitle"); } /** * Get the value of the '<code>featuredChannelsTitle</code>' attribute. */ const StringPiece get_featured_channels_title() const { const Json::Value& v = Storage("featuredChannelsTitle"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>featuredChannelsTitle</code>' attribute. * * Title for the featured channels tab. * * @param[in] value The new value. */ void set_featured_channels_title(const StringPiece& value) { *MutableStorage("featuredChannelsTitle") = value.data(); } /** * Determine if the '<code>featuredChannelsUrls</code>' attribute was set. * * @return true if the '<code>featuredChannelsUrls</code>' attribute was set. */ bool has_featured_channels_urls() const { return Storage().isMember("featuredChannelsUrls"); } /** * Clears the '<code>featuredChannelsUrls</code>' attribute. */ void clear_featured_channels_urls() { MutableStorage()->removeMember("featuredChannelsUrls"); } /** * Get a reference to the value of the '<code>featuredChannelsUrls</code>' * attribute. */ const client::JsonCppArray<string > get_featured_channels_urls() const { const Json::Value& storage = Storage("featuredChannelsUrls"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the * '<code>featuredChannelsUrls</code>' property. * * The list of featured channels. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_featuredChannelsUrls() { Json::Value* storage = MutableStorage("featuredChannelsUrls"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>keywords</code>' attribute was set. * * @return true if the '<code>keywords</code>' attribute was set. */ bool has_keywords() const { return Storage().isMember("keywords"); } /** * Clears the '<code>keywords</code>' attribute. */ void clear_keywords() { MutableStorage()->removeMember("keywords"); } /** * Get the value of the '<code>keywords</code>' attribute. */ const StringPiece get_keywords() const { const Json::Value& v = Storage("keywords"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>keywords</code>' attribute. * * Lists keywords associated with the channel, comma-separated. * * @param[in] value The new value. */ void set_keywords(const StringPiece& value) { *MutableStorage("keywords") = value.data(); } /** * Determine if the '<code>moderateComments</code>' attribute was set. * * @return true if the '<code>moderateComments</code>' attribute was set. */ bool has_moderate_comments() const { return Storage().isMember("moderateComments"); } /** * Clears the '<code>moderateComments</code>' attribute. */ void clear_moderate_comments() { MutableStorage()->removeMember("moderateComments"); } /** * Get the value of the '<code>moderateComments</code>' attribute. */ bool get_moderate_comments() const { const Json::Value& storage = Storage("moderateComments"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>moderateComments</code>' attribute. * * Whether user-submitted comments left on the channel page need to be * approved by the channel owner to be publicly visible. * * @param[in] value The new value. */ void set_moderate_comments(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("moderateComments")); } /** * Determine if the '<code>profileColor</code>' attribute was set. * * @return true if the '<code>profileColor</code>' attribute was set. */ bool has_profile_color() const { return Storage().isMember("profileColor"); } /** * Clears the '<code>profileColor</code>' attribute. */ void clear_profile_color() { MutableStorage()->removeMember("profileColor"); } /** * Get the value of the '<code>profileColor</code>' attribute. */ const StringPiece get_profile_color() const { const Json::Value& v = Storage("profileColor"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>profileColor</code>' attribute. * * A prominent color that can be rendered on this channel page. * * @param[in] value The new value. */ void set_profile_color(const StringPiece& value) { *MutableStorage("profileColor") = value.data(); } /** * Determine if the '<code>showBrowseView</code>' attribute was set. * * @return true if the '<code>showBrowseView</code>' attribute was set. */ bool has_show_browse_view() const { return Storage().isMember("showBrowseView"); } /** * Clears the '<code>showBrowseView</code>' attribute. */ void clear_show_browse_view() { MutableStorage()->removeMember("showBrowseView"); } /** * Get the value of the '<code>showBrowseView</code>' attribute. */ bool get_show_browse_view() const { const Json::Value& storage = Storage("showBrowseView"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>showBrowseView</code>' attribute. * * Whether the tab to browse the videos should be displayed. * * @param[in] value The new value. */ void set_show_browse_view(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("showBrowseView")); } /** * Determine if the '<code>showRelatedChannels</code>' attribute was set. * * @return true if the '<code>showRelatedChannels</code>' attribute was set. */ bool has_show_related_channels() const { return Storage().isMember("showRelatedChannels"); } /** * Clears the '<code>showRelatedChannels</code>' attribute. */ void clear_show_related_channels() { MutableStorage()->removeMember("showRelatedChannels"); } /** * Get the value of the '<code>showRelatedChannels</code>' attribute. */ bool get_show_related_channels() const { const Json::Value& storage = Storage("showRelatedChannels"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>showRelatedChannels</code>' attribute. * * Whether related channels should be proposed. * * @param[in] value The new value. */ void set_show_related_channels(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("showRelatedChannels")); } /** * Determine if the '<code>title</code>' attribute was set. * * @return true if the '<code>title</code>' attribute was set. */ bool has_title() const { return Storage().isMember("title"); } /** * Clears the '<code>title</code>' attribute. */ void clear_title() { MutableStorage()->removeMember("title"); } /** * Get the value of the '<code>title</code>' attribute. */ const StringPiece get_title() const { const Json::Value& v = Storage("title"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>title</code>' attribute. * * Specifies the channel title. * * @param[in] value The new value. */ void set_title(const StringPiece& value) { *MutableStorage("title") = value.data(); } /** * Determine if the '<code>trackingAnalyticsAccountId</code>' attribute was * set. * * @return true if the '<code>trackingAnalyticsAccountId</code>' attribute was * set. */ bool has_tracking_analytics_account_id() const { return Storage().isMember("trackingAnalyticsAccountId"); } /** * Clears the '<code>trackingAnalyticsAccountId</code>' attribute. */ void clear_tracking_analytics_account_id() { MutableStorage()->removeMember("trackingAnalyticsAccountId"); } /** * Get the value of the '<code>trackingAnalyticsAccountId</code>' attribute. */ const StringPiece get_tracking_analytics_account_id() const { const Json::Value& v = Storage("trackingAnalyticsAccountId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>trackingAnalyticsAccountId</code>' attribute. * * The ID for a Google Analytics account to track and measure traffic to the * channels. * * @param[in] value The new value. */ void set_tracking_analytics_account_id(const StringPiece& value) { *MutableStorage("trackingAnalyticsAccountId") = value.data(); } /** * Determine if the '<code>unsubscribedTrailer</code>' attribute was set. * * @return true if the '<code>unsubscribedTrailer</code>' attribute was set. */ bool has_unsubscribed_trailer() const { return Storage().isMember("unsubscribedTrailer"); } /** * Clears the '<code>unsubscribedTrailer</code>' attribute. */ void clear_unsubscribed_trailer() { MutableStorage()->removeMember("unsubscribedTrailer"); } /** * Get the value of the '<code>unsubscribedTrailer</code>' attribute. */ const StringPiece get_unsubscribed_trailer() const { const Json::Value& v = Storage("unsubscribedTrailer"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>unsubscribedTrailer</code>' attribute. * * The trailer of the channel, for users that are not subscribers. * * @param[in] value The new value. */ void set_unsubscribed_trailer(const StringPiece& value) { *MutableStorage("unsubscribedTrailer") = value.data(); } private: void operator=(const ChannelSettings&); }; // ChannelSettings } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_CHANNEL_SETTINGS_H_ <file_sep>/service_apis/youtube/google/youtube_api/channel_audit_details.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_CHANNEL_AUDIT_DETAILS_H_ #define GOOGLE_YOUTUBE_API_CHANNEL_AUDIT_DETAILS_H_ #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * The auditDetails object encapsulates channel data that is relevant for * YouTube Partners during the audit process. * * @ingroup DataObject */ class ChannelAuditDetails : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static ChannelAuditDetails* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelAuditDetails(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelAuditDetails(Json::Value* storage); /** * Standard destructor. */ virtual ~ChannelAuditDetails(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::ChannelAuditDetails</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::ChannelAuditDetails"); } /** * Determine if the '<code>communityGuidelinesGoodStanding</code>' attribute * was set. * * @return true if the '<code>communityGuidelinesGoodStanding</code>' * attribute was set. */ bool has_community_guidelines_good_standing() const { return Storage().isMember("communityGuidelinesGoodStanding"); } /** * Clears the '<code>communityGuidelinesGoodStanding</code>' attribute. */ void clear_community_guidelines_good_standing() { MutableStorage()->removeMember("communityGuidelinesGoodStanding"); } /** * Get the value of the '<code>communityGuidelinesGoodStanding</code>' * attribute. */ bool get_community_guidelines_good_standing() const { const Json::Value& storage = Storage("communityGuidelinesGoodStanding"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>communityGuidelinesGoodStanding</code>' attribute. * * Whether or not the channel respects the community guidelines. * * @param[in] value The new value. */ void set_community_guidelines_good_standing(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("communityGuidelinesGoodStanding")); } /** * Determine if the '<code>contentIdClaimsGoodStanding</code>' attribute was * set. * * @return true if the '<code>contentIdClaimsGoodStanding</code>' attribute * was set. */ bool has_content_id_claims_good_standing() const { return Storage().isMember("contentIdClaimsGoodStanding"); } /** * Clears the '<code>contentIdClaimsGoodStanding</code>' attribute. */ void clear_content_id_claims_good_standing() { MutableStorage()->removeMember("contentIdClaimsGoodStanding"); } /** * Get the value of the '<code>contentIdClaimsGoodStanding</code>' attribute. */ bool get_content_id_claims_good_standing() const { const Json::Value& storage = Storage("contentIdClaimsGoodStanding"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>contentIdClaimsGoodStanding</code>' attribute. * * Whether or not the channel has any unresolved claims. * * @param[in] value The new value. */ void set_content_id_claims_good_standing(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("contentIdClaimsGoodStanding")); } /** * Determine if the '<code>copyrightStrikesGoodStanding</code>' attribute was * set. * * @return true if the '<code>copyrightStrikesGoodStanding</code>' attribute * was set. */ bool has_copyright_strikes_good_standing() const { return Storage().isMember("copyrightStrikesGoodStanding"); } /** * Clears the '<code>copyrightStrikesGoodStanding</code>' attribute. */ void clear_copyright_strikes_good_standing() { MutableStorage()->removeMember("copyrightStrikesGoodStanding"); } /** * Get the value of the '<code>copyrightStrikesGoodStanding</code>' attribute. */ bool get_copyright_strikes_good_standing() const { const Json::Value& storage = Storage("copyrightStrikesGoodStanding"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>copyrightStrikesGoodStanding</code>' attribute. * * Whether or not the channel has any copyright strikes. * * @param[in] value The new value. */ void set_copyright_strikes_good_standing(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("copyrightStrikesGoodStanding")); } /** * Determine if the '<code>overallGoodStanding</code>' attribute was set. * * @return true if the '<code>overallGoodStanding</code>' attribute was set. */ bool has_overall_good_standing() const { return Storage().isMember("overallGoodStanding"); } /** * Clears the '<code>overallGoodStanding</code>' attribute. */ void clear_overall_good_standing() { MutableStorage()->removeMember("overallGoodStanding"); } /** * Get the value of the '<code>overallGoodStanding</code>' attribute. */ bool get_overall_good_standing() const { const Json::Value& storage = Storage("overallGoodStanding"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>overallGoodStanding</code>' attribute. * * Describes the general state of the channel. This field will always show if * there are any issues whatsoever with the channel. Currently this field * represents the result of the logical and operation over the community * guidelines good standing, the copyright strikes good standing and the * content ID claims good standing, but this may change in the future. * * @param[in] value The new value. */ void set_overall_good_standing(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("overallGoodStanding")); } private: void operator=(const ChannelAuditDetails&); }; // ChannelAuditDetails } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_CHANNEL_AUDIT_DETAILS_H_ <file_sep>/service_apis/youtube/google/youtube_api/content_rating.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_CONTENT_RATING_H_ #define GOOGLE_YOUTUBE_API_CONTENT_RATING_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Ratings schemes. The country-specific ratings are mostly for movies and * shows. NEXT_ID: 69. * * @ingroup DataObject */ class ContentRating : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static ContentRating* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ContentRating(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ContentRating(Json::Value* storage); /** * Standard destructor. */ virtual ~ContentRating(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::ContentRating</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::ContentRating"); } /** * Determine if the '<code>acbRating</code>' attribute was set. * * @return true if the '<code>acbRating</code>' attribute was set. */ bool has_acb_rating() const { return Storage().isMember("acbRating"); } /** * Clears the '<code>acbRating</code>' attribute. */ void clear_acb_rating() { MutableStorage()->removeMember("acbRating"); } /** * Get the value of the '<code>acbRating</code>' attribute. */ const StringPiece get_acb_rating() const { const Json::Value& v = Storage("acbRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>acbRating</code>' attribute. * * The video's Australian Classification Board (ACB) or Australian * Communications and Media Authority (ACMA) rating. ACMA ratings are used to * classify children's television programming. * * @param[in] value The new value. */ void set_acb_rating(const StringPiece& value) { *MutableStorage("acbRating") = value.data(); } /** * Determine if the '<code>agcomRating</code>' attribute was set. * * @return true if the '<code>agcomRating</code>' attribute was set. */ bool has_agcom_rating() const { return Storage().isMember("agcomRating"); } /** * Clears the '<code>agcomRating</code>' attribute. */ void clear_agcom_rating() { MutableStorage()->removeMember("agcomRating"); } /** * Get the value of the '<code>agcomRating</code>' attribute. */ const StringPiece get_agcom_rating() const { const Json::Value& v = Storage("agcomRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>agcomRating</code>' attribute. * * The video's rating from Italy's Autorità per le Garanzie nelle * Comunicazioni (AGCOM). * * @param[in] value The new value. */ void set_agcom_rating(const StringPiece& value) { *MutableStorage("agcomRating") = value.data(); } /** * Determine if the '<code>anatelRating</code>' attribute was set. * * @return true if the '<code>anatelRating</code>' attribute was set. */ bool has_anatel_rating() const { return Storage().isMember("anatelRating"); } /** * Clears the '<code>anatelRating</code>' attribute. */ void clear_anatel_rating() { MutableStorage()->removeMember("anatelRating"); } /** * Get the value of the '<code>anatelRating</code>' attribute. */ const StringPiece get_anatel_rating() const { const Json::Value& v = Storage("anatelRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>anatelRating</code>' attribute. * * The video's Anatel (Asociación Nacional de Televisión) rating for Chilean * television. * * @param[in] value The new value. */ void set_anatel_rating(const StringPiece& value) { *MutableStorage("anatelRating") = value.data(); } /** * Determine if the '<code>bbfcRating</code>' attribute was set. * * @return true if the '<code>bbfcRating</code>' attribute was set. */ bool has_bbfc_rating() const { return Storage().isMember("bbfcRating"); } /** * Clears the '<code>bbfcRating</code>' attribute. */ void clear_bbfc_rating() { MutableStorage()->removeMember("bbfcRating"); } /** * Get the value of the '<code>bbfcRating</code>' attribute. */ const StringPiece get_bbfc_rating() const { const Json::Value& v = Storage("bbfcRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bbfcRating</code>' attribute. * * The video's British Board of Film Classification (BBFC) rating. * * @param[in] value The new value. */ void set_bbfc_rating(const StringPiece& value) { *MutableStorage("bbfcRating") = value.data(); } /** * Determine if the '<code>bfvcRating</code>' attribute was set. * * @return true if the '<code>bfvcRating</code>' attribute was set. */ bool has_bfvc_rating() const { return Storage().isMember("bfvcRating"); } /** * Clears the '<code>bfvcRating</code>' attribute. */ void clear_bfvc_rating() { MutableStorage()->removeMember("bfvcRating"); } /** * Get the value of the '<code>bfvcRating</code>' attribute. */ const StringPiece get_bfvc_rating() const { const Json::Value& v = Storage("bfvcRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bfvcRating</code>' attribute. * * The video's rating from Thailand's Board of Film and Video Censors. * * @param[in] value The new value. */ void set_bfvc_rating(const StringPiece& value) { *MutableStorage("bfvcRating") = value.data(); } /** * Determine if the '<code>bmukkRating</code>' attribute was set. * * @return true if the '<code>bmukkRating</code>' attribute was set. */ bool has_bmukk_rating() const { return Storage().isMember("bmukkRating"); } /** * Clears the '<code>bmukkRating</code>' attribute. */ void clear_bmukk_rating() { MutableStorage()->removeMember("bmukkRating"); } /** * Get the value of the '<code>bmukkRating</code>' attribute. */ const StringPiece get_bmukk_rating() const { const Json::Value& v = Storage("bmukkRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bmukkRating</code>' attribute. * * The video's rating from the Austrian Board of Media Classification * (Bundesministerium für Unterricht, Kunst und Kultur). * * @param[in] value The new value. */ void set_bmukk_rating(const StringPiece& value) { *MutableStorage("bmukkRating") = value.data(); } /** * Determine if the '<code>catvRating</code>' attribute was set. * * @return true if the '<code>catvRating</code>' attribute was set. */ bool has_catv_rating() const { return Storage().isMember("catvRating"); } /** * Clears the '<code>catvRating</code>' attribute. */ void clear_catv_rating() { MutableStorage()->removeMember("catvRating"); } /** * Get the value of the '<code>catvRating</code>' attribute. */ const StringPiece get_catv_rating() const { const Json::Value& v = Storage("catvRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>catvRating</code>' attribute. * * Rating system for Canadian TV - Canadian TV Classification System The * video's rating from the Canadian Radio-Television and Telecommunications * Commission (CRTC) for Canadian English-language broadcasts. For more * information, see the Canadian Broadcast Standards Council website. * * @param[in] value The new value. */ void set_catv_rating(const StringPiece& value) { *MutableStorage("catvRating") = value.data(); } /** * Determine if the '<code>catvfrRating</code>' attribute was set. * * @return true if the '<code>catvfrRating</code>' attribute was set. */ bool has_catvfr_rating() const { return Storage().isMember("catvfrRating"); } /** * Clears the '<code>catvfrRating</code>' attribute. */ void clear_catvfr_rating() { MutableStorage()->removeMember("catvfrRating"); } /** * Get the value of the '<code>catvfrRating</code>' attribute. */ const StringPiece get_catvfr_rating() const { const Json::Value& v = Storage("catvfrRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>catvfrRating</code>' attribute. * * The video's rating from the Canadian Radio-Television and * Telecommunications Commission (CRTC) for Canadian French-language * broadcasts. For more information, see the Canadian Broadcast Standards * Council website. * * @param[in] value The new value. */ void set_catvfr_rating(const StringPiece& value) { *MutableStorage("catvfrRating") = value.data(); } /** * Determine if the '<code>cbfcRating</code>' attribute was set. * * @return true if the '<code>cbfcRating</code>' attribute was set. */ bool has_cbfc_rating() const { return Storage().isMember("cbfcRating"); } /** * Clears the '<code>cbfcRating</code>' attribute. */ void clear_cbfc_rating() { MutableStorage()->removeMember("cbfcRating"); } /** * Get the value of the '<code>cbfcRating</code>' attribute. */ const StringPiece get_cbfc_rating() const { const Json::Value& v = Storage("cbfcRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>cbfcRating</code>' attribute. * * The video's Central Board of Film Certification (CBFC - India) rating. * * @param[in] value The new value. */ void set_cbfc_rating(const StringPiece& value) { *MutableStorage("cbfcRating") = value.data(); } /** * Determine if the '<code>cccRating</code>' attribute was set. * * @return true if the '<code>cccRating</code>' attribute was set. */ bool has_ccc_rating() const { return Storage().isMember("cccRating"); } /** * Clears the '<code>cccRating</code>' attribute. */ void clear_ccc_rating() { MutableStorage()->removeMember("cccRating"); } /** * Get the value of the '<code>cccRating</code>' attribute. */ const StringPiece get_ccc_rating() const { const Json::Value& v = Storage("cccRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>cccRating</code>' attribute. * * The video's Consejo de Calificación Cinematográfica (Chile) rating. * * @param[in] value The new value. */ void set_ccc_rating(const StringPiece& value) { *MutableStorage("cccRating") = value.data(); } /** * Determine if the '<code>cceRating</code>' attribute was set. * * @return true if the '<code>cceRating</code>' attribute was set. */ bool has_cce_rating() const { return Storage().isMember("cceRating"); } /** * Clears the '<code>cceRating</code>' attribute. */ void clear_cce_rating() { MutableStorage()->removeMember("cceRating"); } /** * Get the value of the '<code>cceRating</code>' attribute. */ const StringPiece get_cce_rating() const { const Json::Value& v = Storage("cceRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>cceRating</code>' attribute. * * The video's rating from Portugal's Comissão de Classificação de * Espect´culos. * * @param[in] value The new value. */ void set_cce_rating(const StringPiece& value) { *MutableStorage("cceRating") = value.data(); } /** * Determine if the '<code>chfilmRating</code>' attribute was set. * * @return true if the '<code>chfilmRating</code>' attribute was set. */ bool has_chfilm_rating() const { return Storage().isMember("chfilmRating"); } /** * Clears the '<code>chfilmRating</code>' attribute. */ void clear_chfilm_rating() { MutableStorage()->removeMember("chfilmRating"); } /** * Get the value of the '<code>chfilmRating</code>' attribute. */ const StringPiece get_chfilm_rating() const { const Json::Value& v = Storage("chfilmRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>chfilmRating</code>' attribute. * * The video's rating in Switzerland. * * @param[in] value The new value. */ void set_chfilm_rating(const StringPiece& value) { *MutableStorage("chfilmRating") = value.data(); } /** * Determine if the '<code>chvrsRating</code>' attribute was set. * * @return true if the '<code>chvrsRating</code>' attribute was set. */ bool has_chvrs_rating() const { return Storage().isMember("chvrsRating"); } /** * Clears the '<code>chvrsRating</code>' attribute. */ void clear_chvrs_rating() { MutableStorage()->removeMember("chvrsRating"); } /** * Get the value of the '<code>chvrsRating</code>' attribute. */ const StringPiece get_chvrs_rating() const { const Json::Value& v = Storage("chvrsRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>chvrsRating</code>' attribute. * * The video's Canadian Home Video Rating System (CHVRS) rating. * * @param[in] value The new value. */ void set_chvrs_rating(const StringPiece& value) { *MutableStorage("chvrsRating") = value.data(); } /** * Determine if the '<code>cicfRating</code>' attribute was set. * * @return true if the '<code>cicfRating</code>' attribute was set. */ bool has_cicf_rating() const { return Storage().isMember("cicfRating"); } /** * Clears the '<code>cicfRating</code>' attribute. */ void clear_cicf_rating() { MutableStorage()->removeMember("cicfRating"); } /** * Get the value of the '<code>cicfRating</code>' attribute. */ const StringPiece get_cicf_rating() const { const Json::Value& v = Storage("cicfRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>cicfRating</code>' attribute. * * The video's rating from the Commission de Contrôle des Films (Belgium). * * @param[in] value The new value. */ void set_cicf_rating(const StringPiece& value) { *MutableStorage("cicfRating") = value.data(); } /** * Determine if the '<code>cnaRating</code>' attribute was set. * * @return true if the '<code>cnaRating</code>' attribute was set. */ bool has_cna_rating() const { return Storage().isMember("cnaRating"); } /** * Clears the '<code>cnaRating</code>' attribute. */ void clear_cna_rating() { MutableStorage()->removeMember("cnaRating"); } /** * Get the value of the '<code>cnaRating</code>' attribute. */ const StringPiece get_cna_rating() const { const Json::Value& v = Storage("cnaRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>cnaRating</code>' attribute. * * The video's rating from Romania's CONSILIUL NATIONAL AL AUDIOVIZUALULUI * (CNA). * * @param[in] value The new value. */ void set_cna_rating(const StringPiece& value) { *MutableStorage("cnaRating") = value.data(); } /** * Determine if the '<code>cncRating</code>' attribute was set. * * @return true if the '<code>cncRating</code>' attribute was set. */ bool has_cnc_rating() const { return Storage().isMember("cncRating"); } /** * Clears the '<code>cncRating</code>' attribute. */ void clear_cnc_rating() { MutableStorage()->removeMember("cncRating"); } /** * Get the value of the '<code>cncRating</code>' attribute. */ const StringPiece get_cnc_rating() const { const Json::Value& v = Storage("cncRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>cncRating</code>' attribute. * * Rating system in France - Commission de classification cinematographique. * * @param[in] value The new value. */ void set_cnc_rating(const StringPiece& value) { *MutableStorage("cncRating") = value.data(); } /** * Determine if the '<code>csaRating</code>' attribute was set. * * @return true if the '<code>csaRating</code>' attribute was set. */ bool has_csa_rating() const { return Storage().isMember("csaRating"); } /** * Clears the '<code>csaRating</code>' attribute. */ void clear_csa_rating() { MutableStorage()->removeMember("csaRating"); } /** * Get the value of the '<code>csaRating</code>' attribute. */ const StringPiece get_csa_rating() const { const Json::Value& v = Storage("csaRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>csaRating</code>' attribute. * * The video's rating from France's Conseil supérieur de l?audiovisuel, which * rates broadcast content. * * @param[in] value The new value. */ void set_csa_rating(const StringPiece& value) { *MutableStorage("csaRating") = value.data(); } /** * Determine if the '<code>cscfRating</code>' attribute was set. * * @return true if the '<code>cscfRating</code>' attribute was set. */ bool has_cscf_rating() const { return Storage().isMember("cscfRating"); } /** * Clears the '<code>cscfRating</code>' attribute. */ void clear_cscf_rating() { MutableStorage()->removeMember("cscfRating"); } /** * Get the value of the '<code>cscfRating</code>' attribute. */ const StringPiece get_cscf_rating() const { const Json::Value& v = Storage("cscfRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>cscfRating</code>' attribute. * * The video's rating from Luxembourg's Commission de surveillance de la * classification des films (CSCF). * * @param[in] value The new value. */ void set_cscf_rating(const StringPiece& value) { *MutableStorage("cscfRating") = value.data(); } /** * Determine if the '<code>czfilmRating</code>' attribute was set. * * @return true if the '<code>czfilmRating</code>' attribute was set. */ bool has_czfilm_rating() const { return Storage().isMember("czfilmRating"); } /** * Clears the '<code>czfilmRating</code>' attribute. */ void clear_czfilm_rating() { MutableStorage()->removeMember("czfilmRating"); } /** * Get the value of the '<code>czfilmRating</code>' attribute. */ const StringPiece get_czfilm_rating() const { const Json::Value& v = Storage("czfilmRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>czfilmRating</code>' attribute. * * The video's rating in the Czech Republic. * * @param[in] value The new value. */ void set_czfilm_rating(const StringPiece& value) { *MutableStorage("czfilmRating") = value.data(); } /** * Determine if the '<code>djctqRating</code>' attribute was set. * * @return true if the '<code>djctqRating</code>' attribute was set. */ bool has_djctq_rating() const { return Storage().isMember("djctqRating"); } /** * Clears the '<code>djctqRating</code>' attribute. */ void clear_djctq_rating() { MutableStorage()->removeMember("djctqRating"); } /** * Get the value of the '<code>djctqRating</code>' attribute. */ const StringPiece get_djctq_rating() const { const Json::Value& v = Storage("djctqRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>djctqRating</code>' attribute. * * The video's Departamento de Justiça, Classificação, Qualificação e Títulos * (DJCQT - Brazil) rating. * * @param[in] value The new value. */ void set_djctq_rating(const StringPiece& value) { *MutableStorage("djctqRating") = value.data(); } /** * Determine if the '<code>djctqRatingReasons</code>' attribute was set. * * @return true if the '<code>djctqRatingReasons</code>' attribute was set. */ bool has_djctq_rating_reasons() const { return Storage().isMember("djctqRatingReasons"); } /** * Clears the '<code>djctqRatingReasons</code>' attribute. */ void clear_djctq_rating_reasons() { MutableStorage()->removeMember("djctqRatingReasons"); } /** * Get a reference to the value of the '<code>djctqRatingReasons</code>' * attribute. */ const client::JsonCppArray<string > get_djctq_rating_reasons() const { const Json::Value& storage = Storage("djctqRatingReasons"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the * '<code>djctqRatingReasons</code>' property. * * Reasons that explain why the video received its DJCQT (Brazil) rating. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_djctqRatingReasons() { Json::Value* storage = MutableStorage("djctqRatingReasons"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>ecbmctRating</code>' attribute was set. * * @return true if the '<code>ecbmctRating</code>' attribute was set. */ bool has_ecbmct_rating() const { return Storage().isMember("ecbmctRating"); } /** * Clears the '<code>ecbmctRating</code>' attribute. */ void clear_ecbmct_rating() { MutableStorage()->removeMember("ecbmctRating"); } /** * Get the value of the '<code>ecbmctRating</code>' attribute. */ const StringPiece get_ecbmct_rating() const { const Json::Value& v = Storage("ecbmctRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>ecbmctRating</code>' attribute. * * Rating system in Turkey - Evaluation and Classification Board of the * Ministry of Culture and Tourism. * * @param[in] value The new value. */ void set_ecbmct_rating(const StringPiece& value) { *MutableStorage("ecbmctRating") = value.data(); } /** * Determine if the '<code>eefilmRating</code>' attribute was set. * * @return true if the '<code>eefilmRating</code>' attribute was set. */ bool has_eefilm_rating() const { return Storage().isMember("eefilmRating"); } /** * Clears the '<code>eefilmRating</code>' attribute. */ void clear_eefilm_rating() { MutableStorage()->removeMember("eefilmRating"); } /** * Get the value of the '<code>eefilmRating</code>' attribute. */ const StringPiece get_eefilm_rating() const { const Json::Value& v = Storage("eefilmRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>eefilmRating</code>' attribute. * * The video's rating in Estonia. * * @param[in] value The new value. */ void set_eefilm_rating(const StringPiece& value) { *MutableStorage("eefilmRating") = value.data(); } /** * Determine if the '<code>egfilmRating</code>' attribute was set. * * @return true if the '<code>egfilmRating</code>' attribute was set. */ bool has_egfilm_rating() const { return Storage().isMember("egfilmRating"); } /** * Clears the '<code>egfilmRating</code>' attribute. */ void clear_egfilm_rating() { MutableStorage()->removeMember("egfilmRating"); } /** * Get the value of the '<code>egfilmRating</code>' attribute. */ const StringPiece get_egfilm_rating() const { const Json::Value& v = Storage("egfilmRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>egfilmRating</code>' attribute. * * The video's rating in Egypt. * * @param[in] value The new value. */ void set_egfilm_rating(const StringPiece& value) { *MutableStorage("egfilmRating") = value.data(); } /** * Determine if the '<code>eirinRating</code>' attribute was set. * * @return true if the '<code>eirinRating</code>' attribute was set. */ bool has_eirin_rating() const { return Storage().isMember("eirinRating"); } /** * Clears the '<code>eirinRating</code>' attribute. */ void clear_eirin_rating() { MutableStorage()->removeMember("eirinRating"); } /** * Get the value of the '<code>eirinRating</code>' attribute. */ const StringPiece get_eirin_rating() const { const Json::Value& v = Storage("eirinRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>eirinRating</code>' attribute. * * The video's Eirin (映倫) rating. Eirin is the Japanese rating system. * * @param[in] value The new value. */ void set_eirin_rating(const StringPiece& value) { *MutableStorage("eirinRating") = value.data(); } /** * Determine if the '<code>fcbmRating</code>' attribute was set. * * @return true if the '<code>fcbmRating</code>' attribute was set. */ bool has_fcbm_rating() const { return Storage().isMember("fcbmRating"); } /** * Clears the '<code>fcbmRating</code>' attribute. */ void clear_fcbm_rating() { MutableStorage()->removeMember("fcbmRating"); } /** * Get the value of the '<code>fcbmRating</code>' attribute. */ const StringPiece get_fcbm_rating() const { const Json::Value& v = Storage("fcbmRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>fcbmRating</code>' attribute. * * The video's rating from Malaysia's Film Censorship Board. * * @param[in] value The new value. */ void set_fcbm_rating(const StringPiece& value) { *MutableStorage("fcbmRating") = value.data(); } /** * Determine if the '<code>fcoRating</code>' attribute was set. * * @return true if the '<code>fcoRating</code>' attribute was set. */ bool has_fco_rating() const { return Storage().isMember("fcoRating"); } /** * Clears the '<code>fcoRating</code>' attribute. */ void clear_fco_rating() { MutableStorage()->removeMember("fcoRating"); } /** * Get the value of the '<code>fcoRating</code>' attribute. */ const StringPiece get_fco_rating() const { const Json::Value& v = Storage("fcoRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>fcoRating</code>' attribute. * * The video's rating from Hong Kong's Office for Film, Newspaper and Article * Administration. * * @param[in] value The new value. */ void set_fco_rating(const StringPiece& value) { *MutableStorage("fcoRating") = value.data(); } /** * Determine if the '<code>fmocRating</code>' attribute was set. * * @return true if the '<code>fmocRating</code>' attribute was set. */ bool has_fmoc_rating() const { return Storage().isMember("fmocRating"); } /** * Clears the '<code>fmocRating</code>' attribute. */ void clear_fmoc_rating() { MutableStorage()->removeMember("fmocRating"); } /** * Get the value of the '<code>fmocRating</code>' attribute. */ const StringPiece get_fmoc_rating() const { const Json::Value& v = Storage("fmocRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>fmocRating</code>' attribute. * * This property has been deprecated. Use the * contentDetails.contentRating.cncRating instead. * * @param[in] value The new value. */ void set_fmoc_rating(const StringPiece& value) { *MutableStorage("fmocRating") = value.data(); } /** * Determine if the '<code>fpbRating</code>' attribute was set. * * @return true if the '<code>fpbRating</code>' attribute was set. */ bool has_fpb_rating() const { return Storage().isMember("fpbRating"); } /** * Clears the '<code>fpbRating</code>' attribute. */ void clear_fpb_rating() { MutableStorage()->removeMember("fpbRating"); } /** * Get the value of the '<code>fpbRating</code>' attribute. */ const StringPiece get_fpb_rating() const { const Json::Value& v = Storage("fpbRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>fpbRating</code>' attribute. * * The video's rating from South Africa's Film and Publication Board. * * @param[in] value The new value. */ void set_fpb_rating(const StringPiece& value) { *MutableStorage("fpbRating") = value.data(); } /** * Determine if the '<code>fpbRatingReasons</code>' attribute was set. * * @return true if the '<code>fpbRatingReasons</code>' attribute was set. */ bool has_fpb_rating_reasons() const { return Storage().isMember("fpbRatingReasons"); } /** * Clears the '<code>fpbRatingReasons</code>' attribute. */ void clear_fpb_rating_reasons() { MutableStorage()->removeMember("fpbRatingReasons"); } /** * Get a reference to the value of the '<code>fpbRatingReasons</code>' * attribute. */ const client::JsonCppArray<string > get_fpb_rating_reasons() const { const Json::Value& storage = Storage("fpbRatingReasons"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>fpbRatingReasons</code>' * property. * * Reasons that explain why the video received its FPB (South Africa) rating. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_fpbRatingReasons() { Json::Value* storage = MutableStorage("fpbRatingReasons"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>fskRating</code>' attribute was set. * * @return true if the '<code>fskRating</code>' attribute was set. */ bool has_fsk_rating() const { return Storage().isMember("fskRating"); } /** * Clears the '<code>fskRating</code>' attribute. */ void clear_fsk_rating() { MutableStorage()->removeMember("fskRating"); } /** * Get the value of the '<code>fskRating</code>' attribute. */ const StringPiece get_fsk_rating() const { const Json::Value& v = Storage("fskRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>fskRating</code>' attribute. * * The video's Freiwillige Selbstkontrolle der Filmwirtschaft (FSK - Germany) * rating. * * @param[in] value The new value. */ void set_fsk_rating(const StringPiece& value) { *MutableStorage("fskRating") = value.data(); } /** * Determine if the '<code>grfilmRating</code>' attribute was set. * * @return true if the '<code>grfilmRating</code>' attribute was set. */ bool has_grfilm_rating() const { return Storage().isMember("grfilmRating"); } /** * Clears the '<code>grfilmRating</code>' attribute. */ void clear_grfilm_rating() { MutableStorage()->removeMember("grfilmRating"); } /** * Get the value of the '<code>grfilmRating</code>' attribute. */ const StringPiece get_grfilm_rating() const { const Json::Value& v = Storage("grfilmRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>grfilmRating</code>' attribute. * * The video's rating in Greece. * * @param[in] value The new value. */ void set_grfilm_rating(const StringPiece& value) { *MutableStorage("grfilmRating") = value.data(); } /** * Determine if the '<code>icaaRating</code>' attribute was set. * * @return true if the '<code>icaaRating</code>' attribute was set. */ bool has_icaa_rating() const { return Storage().isMember("icaaRating"); } /** * Clears the '<code>icaaRating</code>' attribute. */ void clear_icaa_rating() { MutableStorage()->removeMember("icaaRating"); } /** * Get the value of the '<code>icaaRating</code>' attribute. */ const StringPiece get_icaa_rating() const { const Json::Value& v = Storage("icaaRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>icaaRating</code>' attribute. * * The video's Instituto de la Cinematografía y de las Artes Audiovisuales * (ICAA - Spain) rating. * * @param[in] value The new value. */ void set_icaa_rating(const StringPiece& value) { *MutableStorage("icaaRating") = value.data(); } /** * Determine if the '<code>ifcoRating</code>' attribute was set. * * @return true if the '<code>ifcoRating</code>' attribute was set. */ bool has_ifco_rating() const { return Storage().isMember("ifcoRating"); } /** * Clears the '<code>ifcoRating</code>' attribute. */ void clear_ifco_rating() { MutableStorage()->removeMember("ifcoRating"); } /** * Get the value of the '<code>ifcoRating</code>' attribute. */ const StringPiece get_ifco_rating() const { const Json::Value& v = Storage("ifcoRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>ifcoRating</code>' attribute. * * The video's Irish Film Classification Office (IFCO - Ireland) rating. See * the IFCO website for more information. * * @param[in] value The new value. */ void set_ifco_rating(const StringPiece& value) { *MutableStorage("ifcoRating") = value.data(); } /** * Determine if the '<code>ilfilmRating</code>' attribute was set. * * @return true if the '<code>ilfilmRating</code>' attribute was set. */ bool has_ilfilm_rating() const { return Storage().isMember("ilfilmRating"); } /** * Clears the '<code>ilfilmRating</code>' attribute. */ void clear_ilfilm_rating() { MutableStorage()->removeMember("ilfilmRating"); } /** * Get the value of the '<code>ilfilmRating</code>' attribute. */ const StringPiece get_ilfilm_rating() const { const Json::Value& v = Storage("ilfilmRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>ilfilmRating</code>' attribute. * * The video's rating in Israel. * * @param[in] value The new value. */ void set_ilfilm_rating(const StringPiece& value) { *MutableStorage("ilfilmRating") = value.data(); } /** * Determine if the '<code>incaaRating</code>' attribute was set. * * @return true if the '<code>incaaRating</code>' attribute was set. */ bool has_incaa_rating() const { return Storage().isMember("incaaRating"); } /** * Clears the '<code>incaaRating</code>' attribute. */ void clear_incaa_rating() { MutableStorage()->removeMember("incaaRating"); } /** * Get the value of the '<code>incaaRating</code>' attribute. */ const StringPiece get_incaa_rating() const { const Json::Value& v = Storage("incaaRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>incaaRating</code>' attribute. * * The video's INCAA (Instituto Nacional de Cine y Artes Audiovisuales - * Argentina) rating. * * @param[in] value The new value. */ void set_incaa_rating(const StringPiece& value) { *MutableStorage("incaaRating") = value.data(); } /** * Determine if the '<code>kfcbRating</code>' attribute was set. * * @return true if the '<code>kfcbRating</code>' attribute was set. */ bool has_kfcb_rating() const { return Storage().isMember("kfcbRating"); } /** * Clears the '<code>kfcbRating</code>' attribute. */ void clear_kfcb_rating() { MutableStorage()->removeMember("kfcbRating"); } /** * Get the value of the '<code>kfcbRating</code>' attribute. */ const StringPiece get_kfcb_rating() const { const Json::Value& v = Storage("kfcbRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kfcbRating</code>' attribute. * * The video's rating from the Kenya Film Classification Board. * * @param[in] value The new value. */ void set_kfcb_rating(const StringPiece& value) { *MutableStorage("kfcbRating") = value.data(); } /** * Determine if the '<code>kijkwijzerRating</code>' attribute was set. * * @return true if the '<code>kijkwijzerRating</code>' attribute was set. */ bool has_kijkwijzer_rating() const { return Storage().isMember("kijkwijzerRating"); } /** * Clears the '<code>kijkwijzerRating</code>' attribute. */ void clear_kijkwijzer_rating() { MutableStorage()->removeMember("kijkwijzerRating"); } /** * Get the value of the '<code>kijkwijzerRating</code>' attribute. */ const StringPiece get_kijkwijzer_rating() const { const Json::Value& v = Storage("kijkwijzerRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kijkwijzerRating</code>' attribute. * * voor de Classificatie van Audiovisuele Media (Netherlands). * * @param[in] value The new value. */ void set_kijkwijzer_rating(const StringPiece& value) { *MutableStorage("kijkwijzerRating") = value.data(); } /** * Determine if the '<code>kmrbRating</code>' attribute was set. * * @return true if the '<code>kmrbRating</code>' attribute was set. */ bool has_kmrb_rating() const { return Storage().isMember("kmrbRating"); } /** * Clears the '<code>kmrbRating</code>' attribute. */ void clear_kmrb_rating() { MutableStorage()->removeMember("kmrbRating"); } /** * Get the value of the '<code>kmrbRating</code>' attribute. */ const StringPiece get_kmrb_rating() const { const Json::Value& v = Storage("kmrbRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kmrbRating</code>' attribute. * * The video's Korea Media Rating Board (영상물등급위원회) rating. The KMRB rates * videos in South Korea. * * @param[in] value The new value. */ void set_kmrb_rating(const StringPiece& value) { *MutableStorage("kmrbRating") = value.data(); } /** * Determine if the '<code>lsfRating</code>' attribute was set. * * @return true if the '<code>lsfRating</code>' attribute was set. */ bool has_lsf_rating() const { return Storage().isMember("lsfRating"); } /** * Clears the '<code>lsfRating</code>' attribute. */ void clear_lsf_rating() { MutableStorage()->removeMember("lsfRating"); } /** * Get the value of the '<code>lsfRating</code>' attribute. */ const StringPiece get_lsf_rating() const { const Json::Value& v = Storage("lsfRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>lsfRating</code>' attribute. * * The video's rating from Indonesia's Lembaga Sensor Film. * * @param[in] value The new value. */ void set_lsf_rating(const StringPiece& value) { *MutableStorage("lsfRating") = value.data(); } /** * Determine if the '<code>mccaaRating</code>' attribute was set. * * @return true if the '<code>mccaaRating</code>' attribute was set. */ bool has_mccaa_rating() const { return Storage().isMember("mccaaRating"); } /** * Clears the '<code>mccaaRating</code>' attribute. */ void clear_mccaa_rating() { MutableStorage()->removeMember("mccaaRating"); } /** * Get the value of the '<code>mccaaRating</code>' attribute. */ const StringPiece get_mccaa_rating() const { const Json::Value& v = Storage("mccaaRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>mccaaRating</code>' attribute. * * The video's rating from Malta's Film Age-Classification Board. * * @param[in] value The new value. */ void set_mccaa_rating(const StringPiece& value) { *MutableStorage("mccaaRating") = value.data(); } /** * Determine if the '<code>mccypRating</code>' attribute was set. * * @return true if the '<code>mccypRating</code>' attribute was set. */ bool has_mccyp_rating() const { return Storage().isMember("mccypRating"); } /** * Clears the '<code>mccypRating</code>' attribute. */ void clear_mccyp_rating() { MutableStorage()->removeMember("mccypRating"); } /** * Get the value of the '<code>mccypRating</code>' attribute. */ const StringPiece get_mccyp_rating() const { const Json::Value& v = Storage("mccypRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>mccypRating</code>' attribute. * * The video's rating from the Danish Film Institute's (Det Danske * Filminstitut) Media Council for Children and Young People. * * @param[in] value The new value. */ void set_mccyp_rating(const StringPiece& value) { *MutableStorage("mccypRating") = value.data(); } /** * Determine if the '<code>mcstRating</code>' attribute was set. * * @return true if the '<code>mcstRating</code>' attribute was set. */ bool has_mcst_rating() const { return Storage().isMember("mcstRating"); } /** * Clears the '<code>mcstRating</code>' attribute. */ void clear_mcst_rating() { MutableStorage()->removeMember("mcstRating"); } /** * Get the value of the '<code>mcstRating</code>' attribute. */ const StringPiece get_mcst_rating() const { const Json::Value& v = Storage("mcstRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>mcstRating</code>' attribute. * * The video's rating system for Vietnam - MCST. * * @param[in] value The new value. */ void set_mcst_rating(const StringPiece& value) { *MutableStorage("mcstRating") = value.data(); } /** * Determine if the '<code>mdaRating</code>' attribute was set. * * @return true if the '<code>mdaRating</code>' attribute was set. */ bool has_mda_rating() const { return Storage().isMember("mdaRating"); } /** * Clears the '<code>mdaRating</code>' attribute. */ void clear_mda_rating() { MutableStorage()->removeMember("mdaRating"); } /** * Get the value of the '<code>mdaRating</code>' attribute. */ const StringPiece get_mda_rating() const { const Json::Value& v = Storage("mdaRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>mdaRating</code>' attribute. * * The video's rating from Singapore's Media Development Authority (MDA) and, * specifically, it's Board of Film Censors (BFC). * * @param[in] value The new value. */ void set_mda_rating(const StringPiece& value) { *MutableStorage("mdaRating") = value.data(); } /** * Determine if the '<code>medietilsynetRating</code>' attribute was set. * * @return true if the '<code>medietilsynetRating</code>' attribute was set. */ bool has_medietilsynet_rating() const { return Storage().isMember("medietilsynetRating"); } /** * Clears the '<code>medietilsynetRating</code>' attribute. */ void clear_medietilsynet_rating() { MutableStorage()->removeMember("medietilsynetRating"); } /** * Get the value of the '<code>medietilsynetRating</code>' attribute. */ const StringPiece get_medietilsynet_rating() const { const Json::Value& v = Storage("medietilsynetRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>medietilsynetRating</code>' attribute. * * The video's rating from Medietilsynet, the Norwegian Media Authority. * * @param[in] value The new value. */ void set_medietilsynet_rating(const StringPiece& value) { *MutableStorage("medietilsynetRating") = value.data(); } /** * Determine if the '<code>mekuRating</code>' attribute was set. * * @return true if the '<code>mekuRating</code>' attribute was set. */ bool has_meku_rating() const { return Storage().isMember("mekuRating"); } /** * Clears the '<code>mekuRating</code>' attribute. */ void clear_meku_rating() { MutableStorage()->removeMember("mekuRating"); } /** * Get the value of the '<code>mekuRating</code>' attribute. */ const StringPiece get_meku_rating() const { const Json::Value& v = Storage("mekuRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>mekuRating</code>' attribute. * * The video's rating from Finland's Kansallinen Audiovisuaalinen Instituutti * (National Audiovisual Institute). * * @param[in] value The new value. */ void set_meku_rating(const StringPiece& value) { *MutableStorage("mekuRating") = value.data(); } /** * Determine if the '<code>mibacRating</code>' attribute was set. * * @return true if the '<code>mibacRating</code>' attribute was set. */ bool has_mibac_rating() const { return Storage().isMember("mibacRating"); } /** * Clears the '<code>mibacRating</code>' attribute. */ void clear_mibac_rating() { MutableStorage()->removeMember("mibacRating"); } /** * Get the value of the '<code>mibacRating</code>' attribute. */ const StringPiece get_mibac_rating() const { const Json::Value& v = Storage("mibacRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>mibacRating</code>' attribute. * * The video's rating from the Ministero dei Beni e delle Attività Culturali e * del Turismo (Italy). * * @param[in] value The new value. */ void set_mibac_rating(const StringPiece& value) { *MutableStorage("mibacRating") = value.data(); } /** * Determine if the '<code>mocRating</code>' attribute was set. * * @return true if the '<code>mocRating</code>' attribute was set. */ bool has_moc_rating() const { return Storage().isMember("mocRating"); } /** * Clears the '<code>mocRating</code>' attribute. */ void clear_moc_rating() { MutableStorage()->removeMember("mocRating"); } /** * Get the value of the '<code>mocRating</code>' attribute. */ const StringPiece get_moc_rating() const { const Json::Value& v = Storage("mocRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>mocRating</code>' attribute. * * The video's Ministerio de Cultura (Colombia) rating. * * @param[in] value The new value. */ void set_moc_rating(const StringPiece& value) { *MutableStorage("mocRating") = value.data(); } /** * Determine if the '<code>moctwRating</code>' attribute was set. * * @return true if the '<code>moctwRating</code>' attribute was set. */ bool has_moctw_rating() const { return Storage().isMember("moctwRating"); } /** * Clears the '<code>moctwRating</code>' attribute. */ void clear_moctw_rating() { MutableStorage()->removeMember("moctwRating"); } /** * Get the value of the '<code>moctwRating</code>' attribute. */ const StringPiece get_moctw_rating() const { const Json::Value& v = Storage("moctwRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>moctwRating</code>' attribute. * * The video's rating from Taiwan's Ministry of Culture (文化部). * * @param[in] value The new value. */ void set_moctw_rating(const StringPiece& value) { *MutableStorage("moctwRating") = value.data(); } /** * Determine if the '<code>mpaaRating</code>' attribute was set. * * @return true if the '<code>mpaaRating</code>' attribute was set. */ bool has_mpaa_rating() const { return Storage().isMember("mpaaRating"); } /** * Clears the '<code>mpaaRating</code>' attribute. */ void clear_mpaa_rating() { MutableStorage()->removeMember("mpaaRating"); } /** * Get the value of the '<code>mpaaRating</code>' attribute. */ const StringPiece get_mpaa_rating() const { const Json::Value& v = Storage("mpaaRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>mpaaRating</code>' attribute. * * The video's Motion Picture Association of America (MPAA) rating. * * @param[in] value The new value. */ void set_mpaa_rating(const StringPiece& value) { *MutableStorage("mpaaRating") = value.data(); } /** * Determine if the '<code>mtrcbRating</code>' attribute was set. * * @return true if the '<code>mtrcbRating</code>' attribute was set. */ bool has_mtrcb_rating() const { return Storage().isMember("mtrcbRating"); } /** * Clears the '<code>mtrcbRating</code>' attribute. */ void clear_mtrcb_rating() { MutableStorage()->removeMember("mtrcbRating"); } /** * Get the value of the '<code>mtrcbRating</code>' attribute. */ const StringPiece get_mtrcb_rating() const { const Json::Value& v = Storage("mtrcbRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>mtrcbRating</code>' attribute. * * The video's rating from the Movie and Television Review and Classification * Board (Philippines). * * @param[in] value The new value. */ void set_mtrcb_rating(const StringPiece& value) { *MutableStorage("mtrcbRating") = value.data(); } /** * Determine if the '<code>nbcRating</code>' attribute was set. * * @return true if the '<code>nbcRating</code>' attribute was set. */ bool has_nbc_rating() const { return Storage().isMember("nbcRating"); } /** * Clears the '<code>nbcRating</code>' attribute. */ void clear_nbc_rating() { MutableStorage()->removeMember("nbcRating"); } /** * Get the value of the '<code>nbcRating</code>' attribute. */ const StringPiece get_nbc_rating() const { const Json::Value& v = Storage("nbcRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>nbcRating</code>' attribute. * * The video's rating from the Maldives National Bureau of Classification. * * @param[in] value The new value. */ void set_nbc_rating(const StringPiece& value) { *MutableStorage("nbcRating") = value.data(); } /** * Determine if the '<code>nbcplRating</code>' attribute was set. * * @return true if the '<code>nbcplRating</code>' attribute was set. */ bool has_nbcpl_rating() const { return Storage().isMember("nbcplRating"); } /** * Clears the '<code>nbcplRating</code>' attribute. */ void clear_nbcpl_rating() { MutableStorage()->removeMember("nbcplRating"); } /** * Get the value of the '<code>nbcplRating</code>' attribute. */ const StringPiece get_nbcpl_rating() const { const Json::Value& v = Storage("nbcplRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>nbcplRating</code>' attribute. * * The video's rating in Poland. * * @param[in] value The new value. */ void set_nbcpl_rating(const StringPiece& value) { *MutableStorage("nbcplRating") = value.data(); } /** * Determine if the '<code>nfrcRating</code>' attribute was set. * * @return true if the '<code>nfrcRating</code>' attribute was set. */ bool has_nfrc_rating() const { return Storage().isMember("nfrcRating"); } /** * Clears the '<code>nfrcRating</code>' attribute. */ void clear_nfrc_rating() { MutableStorage()->removeMember("nfrcRating"); } /** * Get the value of the '<code>nfrcRating</code>' attribute. */ const StringPiece get_nfrc_rating() const { const Json::Value& v = Storage("nfrcRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>nfrcRating</code>' attribute. * * The video's rating from the Bulgarian National Film Center. * * @param[in] value The new value. */ void set_nfrc_rating(const StringPiece& value) { *MutableStorage("nfrcRating") = value.data(); } /** * Determine if the '<code>nfvcbRating</code>' attribute was set. * * @return true if the '<code>nfvcbRating</code>' attribute was set. */ bool has_nfvcb_rating() const { return Storage().isMember("nfvcbRating"); } /** * Clears the '<code>nfvcbRating</code>' attribute. */ void clear_nfvcb_rating() { MutableStorage()->removeMember("nfvcbRating"); } /** * Get the value of the '<code>nfvcbRating</code>' attribute. */ const StringPiece get_nfvcb_rating() const { const Json::Value& v = Storage("nfvcbRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>nfvcbRating</code>' attribute. * * The video's rating from Nigeria's National Film and Video Censors Board. * * @param[in] value The new value. */ void set_nfvcb_rating(const StringPiece& value) { *MutableStorage("nfvcbRating") = value.data(); } /** * Determine if the '<code>nkclvRating</code>' attribute was set. * * @return true if the '<code>nkclvRating</code>' attribute was set. */ bool has_nkclv_rating() const { return Storage().isMember("nkclvRating"); } /** * Clears the '<code>nkclvRating</code>' attribute. */ void clear_nkclv_rating() { MutableStorage()->removeMember("nkclvRating"); } /** * Get the value of the '<code>nkclvRating</code>' attribute. */ const StringPiece get_nkclv_rating() const { const Json::Value& v = Storage("nkclvRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>nkclvRating</code>' attribute. * * The video's rating from the Nacionãlais Kino centrs (National Film Centre * of Latvia). * * @param[in] value The new value. */ void set_nkclv_rating(const StringPiece& value) { *MutableStorage("nkclvRating") = value.data(); } /** * Determine if the '<code>oflcRating</code>' attribute was set. * * @return true if the '<code>oflcRating</code>' attribute was set. */ bool has_oflc_rating() const { return Storage().isMember("oflcRating"); } /** * Clears the '<code>oflcRating</code>' attribute. */ void clear_oflc_rating() { MutableStorage()->removeMember("oflcRating"); } /** * Get the value of the '<code>oflcRating</code>' attribute. */ const StringPiece get_oflc_rating() const { const Json::Value& v = Storage("oflcRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>oflcRating</code>' attribute. * * The video's Office of Film and Literature Classification (OFLC - New * Zealand) rating. * * @param[in] value The new value. */ void set_oflc_rating(const StringPiece& value) { *MutableStorage("oflcRating") = value.data(); } /** * Determine if the '<code>pefilmRating</code>' attribute was set. * * @return true if the '<code>pefilmRating</code>' attribute was set. */ bool has_pefilm_rating() const { return Storage().isMember("pefilmRating"); } /** * Clears the '<code>pefilmRating</code>' attribute. */ void clear_pefilm_rating() { MutableStorage()->removeMember("pefilmRating"); } /** * Get the value of the '<code>pefilmRating</code>' attribute. */ const StringPiece get_pefilm_rating() const { const Json::Value& v = Storage("pefilmRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>pefilmRating</code>' attribute. * * The video's rating in Peru. * * @param[in] value The new value. */ void set_pefilm_rating(const StringPiece& value) { *MutableStorage("pefilmRating") = value.data(); } /** * Determine if the '<code>rcnofRating</code>' attribute was set. * * @return true if the '<code>rcnofRating</code>' attribute was set. */ bool has_rcnof_rating() const { return Storage().isMember("rcnofRating"); } /** * Clears the '<code>rcnofRating</code>' attribute. */ void clear_rcnof_rating() { MutableStorage()->removeMember("rcnofRating"); } /** * Get the value of the '<code>rcnofRating</code>' attribute. */ const StringPiece get_rcnof_rating() const { const Json::Value& v = Storage("rcnofRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>rcnofRating</code>' attribute. * * The video's rating from the Hungarian Nemzeti Filmiroda, the Rating * Committee of the National Office of Film. * * @param[in] value The new value. */ void set_rcnof_rating(const StringPiece& value) { *MutableStorage("rcnofRating") = value.data(); } /** * Determine if the '<code>resorteviolenciaRating</code>' attribute was set. * * @return true if the '<code>resorteviolenciaRating</code>' attribute was * set. */ bool has_resorteviolencia_rating() const { return Storage().isMember("resorteviolenciaRating"); } /** * Clears the '<code>resorteviolenciaRating</code>' attribute. */ void clear_resorteviolencia_rating() { MutableStorage()->removeMember("resorteviolenciaRating"); } /** * Get the value of the '<code>resorteviolenciaRating</code>' attribute. */ const StringPiece get_resorteviolencia_rating() const { const Json::Value& v = Storage("resorteviolenciaRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>resorteviolenciaRating</code>' attribute. * * The video's rating in Venezuela. * * @param[in] value The new value. */ void set_resorteviolencia_rating(const StringPiece& value) { *MutableStorage("resorteviolenciaRating") = value.data(); } /** * Determine if the '<code>rtcRating</code>' attribute was set. * * @return true if the '<code>rtcRating</code>' attribute was set. */ bool has_rtc_rating() const { return Storage().isMember("rtcRating"); } /** * Clears the '<code>rtcRating</code>' attribute. */ void clear_rtc_rating() { MutableStorage()->removeMember("rtcRating"); } /** * Get the value of the '<code>rtcRating</code>' attribute. */ const StringPiece get_rtc_rating() const { const Json::Value& v = Storage("rtcRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>rtcRating</code>' attribute. * * The video's General Directorate of Radio, Television and Cinematography * (Mexico) rating. * * @param[in] value The new value. */ void set_rtc_rating(const StringPiece& value) { *MutableStorage("rtcRating") = value.data(); } /** * Determine if the '<code>rteRating</code>' attribute was set. * * @return true if the '<code>rteRating</code>' attribute was set. */ bool has_rte_rating() const { return Storage().isMember("rteRating"); } /** * Clears the '<code>rteRating</code>' attribute. */ void clear_rte_rating() { MutableStorage()->removeMember("rteRating"); } /** * Get the value of the '<code>rteRating</code>' attribute. */ const StringPiece get_rte_rating() const { const Json::Value& v = Storage("rteRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>rteRating</code>' attribute. * * The video's rating from Ireland's Raidió Teilifís Éireann. * * @param[in] value The new value. */ void set_rte_rating(const StringPiece& value) { *MutableStorage("rteRating") = value.data(); } /** * Determine if the '<code>russiaRating</code>' attribute was set. * * @return true if the '<code>russiaRating</code>' attribute was set. */ bool has_russia_rating() const { return Storage().isMember("russiaRating"); } /** * Clears the '<code>russiaRating</code>' attribute. */ void clear_russia_rating() { MutableStorage()->removeMember("russiaRating"); } /** * Get the value of the '<code>russiaRating</code>' attribute. */ const StringPiece get_russia_rating() const { const Json::Value& v = Storage("russiaRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>russiaRating</code>' attribute. * * The video's National Film Registry of the Russian Federation (MKRF - * Russia) rating. * * @param[in] value The new value. */ void set_russia_rating(const StringPiece& value) { *MutableStorage("russiaRating") = value.data(); } /** * Determine if the '<code>skfilmRating</code>' attribute was set. * * @return true if the '<code>skfilmRating</code>' attribute was set. */ bool has_skfilm_rating() const { return Storage().isMember("skfilmRating"); } /** * Clears the '<code>skfilmRating</code>' attribute. */ void clear_skfilm_rating() { MutableStorage()->removeMember("skfilmRating"); } /** * Get the value of the '<code>skfilmRating</code>' attribute. */ const StringPiece get_skfilm_rating() const { const Json::Value& v = Storage("skfilmRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>skfilmRating</code>' attribute. * * The video's rating in Slovakia. * * @param[in] value The new value. */ void set_skfilm_rating(const StringPiece& value) { *MutableStorage("skfilmRating") = value.data(); } /** * Determine if the '<code>smaisRating</code>' attribute was set. * * @return true if the '<code>smaisRating</code>' attribute was set. */ bool has_smais_rating() const { return Storage().isMember("smaisRating"); } /** * Clears the '<code>smaisRating</code>' attribute. */ void clear_smais_rating() { MutableStorage()->removeMember("smaisRating"); } /** * Get the value of the '<code>smaisRating</code>' attribute. */ const StringPiece get_smais_rating() const { const Json::Value& v = Storage("smaisRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>smaisRating</code>' attribute. * * The video's rating in Iceland. * * @param[in] value The new value. */ void set_smais_rating(const StringPiece& value) { *MutableStorage("smaisRating") = value.data(); } /** * Determine if the '<code>smsaRating</code>' attribute was set. * * @return true if the '<code>smsaRating</code>' attribute was set. */ bool has_smsa_rating() const { return Storage().isMember("smsaRating"); } /** * Clears the '<code>smsaRating</code>' attribute. */ void clear_smsa_rating() { MutableStorage()->removeMember("smsaRating"); } /** * Get the value of the '<code>smsaRating</code>' attribute. */ const StringPiece get_smsa_rating() const { const Json::Value& v = Storage("smsaRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>smsaRating</code>' attribute. * * The video's rating from Statens medieråd (Sweden's National Media Council). * * @param[in] value The new value. */ void set_smsa_rating(const StringPiece& value) { *MutableStorage("smsaRating") = value.data(); } /** * Determine if the '<code>tvpgRating</code>' attribute was set. * * @return true if the '<code>tvpgRating</code>' attribute was set. */ bool has_tvpg_rating() const { return Storage().isMember("tvpgRating"); } /** * Clears the '<code>tvpgRating</code>' attribute. */ void clear_tvpg_rating() { MutableStorage()->removeMember("tvpgRating"); } /** * Get the value of the '<code>tvpgRating</code>' attribute. */ const StringPiece get_tvpg_rating() const { const Json::Value& v = Storage("tvpgRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>tvpgRating</code>' attribute. * * The video's TV Parental Guidelines (TVPG) rating. * * @param[in] value The new value. */ void set_tvpg_rating(const StringPiece& value) { *MutableStorage("tvpgRating") = value.data(); } /** * Determine if the '<code>ytRating</code>' attribute was set. * * @return true if the '<code>ytRating</code>' attribute was set. */ bool has_yt_rating() const { return Storage().isMember("ytRating"); } /** * Clears the '<code>ytRating</code>' attribute. */ void clear_yt_rating() { MutableStorage()->removeMember("ytRating"); } /** * Get the value of the '<code>ytRating</code>' attribute. */ const StringPiece get_yt_rating() const { const Json::Value& v = Storage("ytRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>ytRating</code>' attribute. * * A rating that YouTube uses to identify age-restricted content. * * @param[in] value The new value. */ void set_yt_rating(const StringPiece& value) { *MutableStorage("ytRating") = value.data(); } private: void operator=(const ContentRating&); }; // ContentRating } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_CONTENT_RATING_H_ <file_sep>/src/samples/installed_application.h /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ // // An InstalledApplication handles boiler-plate framework code // for the sample applications. It is responsible for managing // the OAuth2 objects. Normally the InstalledServiceApplication // subclass is used to setup and manage the ClientService. // // What makes this an installed application is that it assumes // there is only one user so credentials are not scoped to users. // // TODO(user): 20130110 // It's probably worth folding this into the SDK but I want to // explore it a bit more first. Especially to generalize it // so that it has a sibling class WebApplication. // #ifndef GOOGLEAPIS_SAMPLES_INSTALLED_APPLICATION_H_ #define GOOGLEAPIS_SAMPLES_INSTALLED_APPLICATION_H_ #include <iostream> using std::cout; using std::endl; using std::ostream; // NOLINT #include <memory> #include <string> using std::string; #include <vector> #include "googleapis/client/auth/oauth2_authorization.h" #include "googleapis/client/auth/webserver_authorization_getter.h" #include "googleapis/client/transport/http_transport.h" #include "googleapis/client/util/status.h" #include <glog/logging.h> #include "googleapis/base/macros.h" namespace googleapis { // Maybe this will folded into the toolkit, but for now it's outside. namespace sample { using client::AbstractWebServer; using client::OAuth2Credential; using client::OAuth2AuthorizationFlow; using client::HttpTransport; using client::HttpTransportFactory; // An InstalledApplication manages the OAuth2 setup and credentials // for installed applications. What makes it specific for installed // applications is that it assumes one user for everything. // // TODO(user): 20130118 // Eventually need way to convey errors back to application so they can // choose how to communicate them. class InstalledApplication { public: // Construct an installed application instance. // name is the name of our client application for logging // and tracing purposes. It has no semantic meaning. // // The caller must call Init() to finish initializing the instance // before using it. explicit InstalledApplication(const string& name); virtual ~InstalledApplication(); // Returns the name this instance was constructed with. const string& name() const { return name_; } // Takes ownership of the credential. // // This call performs a lazy initialization of the credential if it was not // already explicitly set. If you are using this in multiple threads, you // should first ensure the credential is created (either ResetCredential or // getting credential() to force the lazy initialization) to avoid the // race condition. void ResetCredential(OAuth2Credential* credential); OAuth2Credential* credential(); // Returns the OAuth2 flow created during Init() OAuth2AuthorizationFlow* flow() { return flow_.get(); } const std::vector<string>& default_oauth2_scopes() const { return default_scopes_; } std::vector<string>* mutable_default_oauth2_scopes() { return &default_scopes_; } // If true then the service credentials will be revoked when this application // is destroyed (i.e. application exists). This is not standard behavior // however may be convienent for tests and trials. void set_revoke_token_on_exit(bool on) { revoke_on_exit_ = on; } bool revoke_token_on_exit() const { return revoke_on_exit_; } const string& user_name() const { return user_name_; } // Change to the given user_name persona. // This will clear the current credential and load a new one. virtual googleapis::util::Status ChangeUser(const string& user_name); // Sets up flow and stuff. If you arent using a client_secrets file then // you at least need to create one defining the flow type then set the // Oauth2ClientSpec in flow()->mutable_client_spec(). googleapis::util::Status Init(const string& client_secrets_path); // This isnt needed if the client_secrets path has a refresh token in it. // But if it doesnt, or was revoked, then you'll need to obtain another one. // This method assists that. virtual googleapis::util::Status AuthorizeClient(); virtual googleapis::util::Status RevokeClient(); virtual googleapis::util::Status StartupHttpd( int port, const string& path, client::WebServerAuthorizationCodeGetter::AskCallback* ask); virtual void ShutdownHttpd(); const client::HttpTransportLayerConfig* config() const { return config_.get(); } client::HttpTransportLayerConfig* mutable_config() { return config_.get(); } protected: // Hook for derived classes to augment Init() virtual googleapis::util::Status InitHelper(); private: string name_; // Only for logging and tracing string user_name_; // User owning credential. // Credentials for implied user. std::unique_ptr<OAuth2Credential> credential_; std::unique_ptr<OAuth2AuthorizationFlow> flow_; // The OAuth2 flow std::vector<string> default_scopes_; // When creating credentials std::unique_ptr<client::HttpTransportLayerConfig> config_; std::unique_ptr<AbstractWebServer> httpd_; // Webserver for getter_ std::unique_ptr<client::WebServerAuthorizationCodeGetter> authorization_code_getter_; bool revoke_on_exit_; DISALLOW_COPY_AND_ASSIGN(InstalledApplication); }; // An installed application client to a specific service. template<class SERVICE> class InstalledServiceApplication : public InstalledApplication { public: explicit InstalledServiceApplication(const string& name) : InstalledApplication(name) { } virtual ~InstalledServiceApplication() {} SERVICE* service() { return service_.get(); } protected: // Hook for derived classes to augment Init(). // This is instead of using InitHelper() offered by the base class. virtual googleapis::util::Status InitServiceHelper() { return client::StatusOk(); } // Derived classes should override InitServiceHelper instead. virtual googleapis::util::Status InitHelper() { HttpTransportFactory* factory = config()->default_transport_factory(); // This shouldn't happen since the Init method calling // this already checks. CHECK(factory); HttpTransport* transport = factory->New(); service_.reset(new SERVICE(transport)); googleapis::util::Status status = InitServiceHelper(); if (!status.ok()) { delete service_.release(); } return status; } private: std::unique_ptr<SERVICE> service_; DISALLOW_COPY_AND_ASSIGN(InstalledServiceApplication); }; } // namespace sample } // namespace googleapis #endif // GOOGLEAPIS_SAMPLES_INSTALLED_APPLICATION_H_ <file_sep>/service_apis/youtube/google/youtube_api/video_status.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_VIDEO_STATUS_H_ #define GOOGLE_YOUTUBE_API_VIDEO_STATUS_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Basic details about a video category, such as its localized title. * * @ingroup DataObject */ class VideoStatus : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static VideoStatus* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoStatus(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoStatus(Json::Value* storage); /** * Standard destructor. */ virtual ~VideoStatus(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::VideoStatus</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::VideoStatus"); } /** * Determine if the '<code>embeddable</code>' attribute was set. * * @return true if the '<code>embeddable</code>' attribute was set. */ bool has_embeddable() const { return Storage().isMember("embeddable"); } /** * Clears the '<code>embeddable</code>' attribute. */ void clear_embeddable() { MutableStorage()->removeMember("embeddable"); } /** * Get the value of the '<code>embeddable</code>' attribute. */ bool get_embeddable() const { const Json::Value& storage = Storage("embeddable"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>embeddable</code>' attribute. * * This value indicates if the video can be embedded on another website. * * @param[in] value The new value. */ void set_embeddable(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("embeddable")); } /** * Determine if the '<code>failureReason</code>' attribute was set. * * @return true if the '<code>failureReason</code>' attribute was set. */ bool has_failure_reason() const { return Storage().isMember("failureReason"); } /** * Clears the '<code>failureReason</code>' attribute. */ void clear_failure_reason() { MutableStorage()->removeMember("failureReason"); } /** * Get the value of the '<code>failureReason</code>' attribute. */ const StringPiece get_failure_reason() const { const Json::Value& v = Storage("failureReason"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>failureReason</code>' attribute. * * This value explains why a video failed to upload. This property is only * present if the uploadStatus property indicates that the upload failed. * * @param[in] value The new value. */ void set_failure_reason(const StringPiece& value) { *MutableStorage("failureReason") = value.data(); } /** * Determine if the '<code>license</code>' attribute was set. * * @return true if the '<code>license</code>' attribute was set. */ bool has_license() const { return Storage().isMember("license"); } /** * Clears the '<code>license</code>' attribute. */ void clear_license() { MutableStorage()->removeMember("license"); } /** * Get the value of the '<code>license</code>' attribute. */ const StringPiece get_license() const { const Json::Value& v = Storage("license"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>license</code>' attribute. * * The video's license. * * @param[in] value The new value. */ void set_license(const StringPiece& value) { *MutableStorage("license") = value.data(); } /** * Determine if the '<code>privacyStatus</code>' attribute was set. * * @return true if the '<code>privacyStatus</code>' attribute was set. */ bool has_privacy_status() const { return Storage().isMember("privacyStatus"); } /** * Clears the '<code>privacyStatus</code>' attribute. */ void clear_privacy_status() { MutableStorage()->removeMember("privacyStatus"); } /** * Get the value of the '<code>privacyStatus</code>' attribute. */ const StringPiece get_privacy_status() const { const Json::Value& v = Storage("privacyStatus"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>privacyStatus</code>' attribute. * * The video's privacy status. * * @param[in] value The new value. */ void set_privacy_status(const StringPiece& value) { *MutableStorage("privacyStatus") = value.data(); } /** * Determine if the '<code>publicStatsViewable</code>' attribute was set. * * @return true if the '<code>publicStatsViewable</code>' attribute was set. */ bool has_public_stats_viewable() const { return Storage().isMember("publicStatsViewable"); } /** * Clears the '<code>publicStatsViewable</code>' attribute. */ void clear_public_stats_viewable() { MutableStorage()->removeMember("publicStatsViewable"); } /** * Get the value of the '<code>publicStatsViewable</code>' attribute. */ bool get_public_stats_viewable() const { const Json::Value& storage = Storage("publicStatsViewable"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>publicStatsViewable</code>' attribute. * * This value indicates if the extended video statistics on the watch page can * be viewed by everyone. Note that the view count, likes, etc will still be * visible if this is disabled. * * @param[in] value The new value. */ void set_public_stats_viewable(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("publicStatsViewable")); } /** * Determine if the '<code>publishAt</code>' attribute was set. * * @return true if the '<code>publishAt</code>' attribute was set. */ bool has_publish_at() const { return Storage().isMember("publishAt"); } /** * Clears the '<code>publishAt</code>' attribute. */ void clear_publish_at() { MutableStorage()->removeMember("publishAt"); } /** * Get the value of the '<code>publishAt</code>' attribute. */ client::DateTime get_publish_at() const { const Json::Value& storage = Storage("publishAt"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>publishAt</code>' attribute. * * The date and time when the video is scheduled to publish. It can be set * only if the privacy status of the video is private. The value is specified * in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. * * @param[in] value The new value. */ void set_publish_at(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("publishAt")); } /** * Determine if the '<code>rejectionReason</code>' attribute was set. * * @return true if the '<code>rejectionReason</code>' attribute was set. */ bool has_rejection_reason() const { return Storage().isMember("rejectionReason"); } /** * Clears the '<code>rejectionReason</code>' attribute. */ void clear_rejection_reason() { MutableStorage()->removeMember("rejectionReason"); } /** * Get the value of the '<code>rejectionReason</code>' attribute. */ const StringPiece get_rejection_reason() const { const Json::Value& v = Storage("rejectionReason"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>rejectionReason</code>' attribute. * * This value explains why YouTube rejected an uploaded video. This property * is only present if the uploadStatus property indicates that the upload was * rejected. * * @param[in] value The new value. */ void set_rejection_reason(const StringPiece& value) { *MutableStorage("rejectionReason") = value.data(); } /** * Determine if the '<code>uploadStatus</code>' attribute was set. * * @return true if the '<code>uploadStatus</code>' attribute was set. */ bool has_upload_status() const { return Storage().isMember("uploadStatus"); } /** * Clears the '<code>uploadStatus</code>' attribute. */ void clear_upload_status() { MutableStorage()->removeMember("uploadStatus"); } /** * Get the value of the '<code>uploadStatus</code>' attribute. */ const StringPiece get_upload_status() const { const Json::Value& v = Storage("uploadStatus"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>uploadStatus</code>' attribute. * * The status of the uploaded video. * * @param[in] value The new value. */ void set_upload_status(const StringPiece& value) { *MutableStorage("uploadStatus") = value.data(); } private: void operator=(const VideoStatus&); }; // VideoStatus } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_VIDEO_STATUS_H_ <file_sep>/service_apis/youtube/google/youtube_api/ingestion_info.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_INGESTION_INFO_H_ #define GOOGLE_YOUTUBE_API_INGESTION_INFO_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Describes information necessary for ingesting an RTMP or an HTTP stream. * * @ingroup DataObject */ class IngestionInfo : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static IngestionInfo* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit IngestionInfo(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit IngestionInfo(Json::Value* storage); /** * Standard destructor. */ virtual ~IngestionInfo(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::IngestionInfo</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::IngestionInfo"); } /** * Determine if the '<code>backupIngestionAddress</code>' attribute was set. * * @return true if the '<code>backupIngestionAddress</code>' attribute was * set. */ bool has_backup_ingestion_address() const { return Storage().isMember("backupIngestionAddress"); } /** * Clears the '<code>backupIngestionAddress</code>' attribute. */ void clear_backup_ingestion_address() { MutableStorage()->removeMember("backupIngestionAddress"); } /** * Get the value of the '<code>backupIngestionAddress</code>' attribute. */ const StringPiece get_backup_ingestion_address() const { const Json::Value& v = Storage("backupIngestionAddress"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>backupIngestionAddress</code>' attribute. * * The backup ingestion URL that you should use to stream video to YouTube. * You have the option of simultaneously streaming the content that you are * sending to the ingestionAddress to this URL. * * @param[in] value The new value. */ void set_backup_ingestion_address(const StringPiece& value) { *MutableStorage("backupIngestionAddress") = value.data(); } /** * Determine if the '<code>ingestionAddress</code>' attribute was set. * * @return true if the '<code>ingestionAddress</code>' attribute was set. */ bool has_ingestion_address() const { return Storage().isMember("ingestionAddress"); } /** * Clears the '<code>ingestionAddress</code>' attribute. */ void clear_ingestion_address() { MutableStorage()->removeMember("ingestionAddress"); } /** * Get the value of the '<code>ingestionAddress</code>' attribute. */ const StringPiece get_ingestion_address() const { const Json::Value& v = Storage("ingestionAddress"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>ingestionAddress</code>' attribute. * * The primary ingestion URL that you should use to stream video to YouTube. * You must stream video to this URL. * * Depending on which application or tool you use to encode your video stream, * you may need to enter the stream URL and stream name separately or you may * need to concatenate them in the following format: * * STREAM_URL/STREAM_NAME. * * @param[in] value The new value. */ void set_ingestion_address(const StringPiece& value) { *MutableStorage("ingestionAddress") = value.data(); } /** * Determine if the '<code>streamName</code>' attribute was set. * * @return true if the '<code>streamName</code>' attribute was set. */ bool has_stream_name() const { return Storage().isMember("streamName"); } /** * Clears the '<code>streamName</code>' attribute. */ void clear_stream_name() { MutableStorage()->removeMember("streamName"); } /** * Get the value of the '<code>streamName</code>' attribute. */ const StringPiece get_stream_name() const { const Json::Value& v = Storage("streamName"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>streamName</code>' attribute. * * The HTTP or RTMP stream name that YouTube assigns to the video stream. * * @param[in] value The new value. */ void set_stream_name(const StringPiece& value) { *MutableStorage("streamName") = value.data(); } private: void operator=(const IngestionInfo&); }; // IngestionInfo } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_INGESTION_INFO_H_ <file_sep>/service_apis/drive/google/drive_api/app.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Drive API (drive/v2) // Generated from: // Version: v2 // Revision: 20170512 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_DRIVE_API_APP_H_ #define GOOGLE_DRIVE_API_APP_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_drive_api { using namespace googleapis; /** * The apps resource provides a list of the apps that a user has installed, with * information about each app's supported MIME types, file extensions, and other * details. * * @ingroup DataObject */ class App : public client::JsonCppData { public: /** * No description provided. * * @ingroup DataObject */ class AppIcons : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static AppIcons* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AppIcons(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AppIcons(Json::Value* storage); /** * Standard destructor. */ virtual ~AppIcons(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::AppIcons</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::AppIcons"); } /** * Determine if the '<code>category</code>' attribute was set. * * @return true if the '<code>category</code>' attribute was set. */ bool has_category() const { return Storage().isMember("category"); } /** * Clears the '<code>category</code>' attribute. */ void clear_category() { MutableStorage()->removeMember("category"); } /** * Get the value of the '<code>category</code>' attribute. */ const StringPiece get_category() const { const Json::Value& v = Storage("category"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>category</code>' attribute. * * Category of the icon. Allowed values are: * <dl> * <dt>application * <dd>icon for the application. * <dt>document * <dd>icon for a file associated with the app. * <dt>documentShared * <dd>icon for a shared file associated with the app. * </dl> * * * @param[in] value The new value. */ void set_category(const StringPiece& value) { *MutableStorage("category") = value.data(); } /** * Determine if the '<code>iconUrl</code>' attribute was set. * * @return true if the '<code>iconUrl</code>' attribute was set. */ bool has_icon_url() const { return Storage().isMember("iconUrl"); } /** * Clears the '<code>iconUrl</code>' attribute. */ void clear_icon_url() { MutableStorage()->removeMember("iconUrl"); } /** * Get the value of the '<code>iconUrl</code>' attribute. */ const StringPiece get_icon_url() const { const Json::Value& v = Storage("iconUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>iconUrl</code>' attribute. * * URL for the icon. * * @param[in] value The new value. */ void set_icon_url(const StringPiece& value) { *MutableStorage("iconUrl") = value.data(); } /** * Determine if the '<code>size</code>' attribute was set. * * @return true if the '<code>size</code>' attribute was set. */ bool has_size() const { return Storage().isMember("size"); } /** * Clears the '<code>size</code>' attribute. */ void clear_size() { MutableStorage()->removeMember("size"); } /** * Get the value of the '<code>size</code>' attribute. */ int32 get_size() const { const Json::Value& storage = Storage("size"); return client::JsonValueToCppValueHelper<int32 >(storage); } /** * Change the '<code>size</code>' attribute. * * Size of the icon. Represented as the maximum of the width and height. * * @param[in] value The new value. */ void set_size(int32 value) { client::SetJsonValueFromCppValueHelper<int32 >( value, MutableStorage("size")); } private: void operator=(const AppIcons&); }; // AppIcons /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static App* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit App(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit App(Json::Value* storage); /** * Standard destructor. */ virtual ~App(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::App</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::App"); } /** * Determine if the '<code>authorized</code>' attribute was set. * * @return true if the '<code>authorized</code>' attribute was set. */ bool has_authorized() const { return Storage().isMember("authorized"); } /** * Clears the '<code>authorized</code>' attribute. */ void clear_authorized() { MutableStorage()->removeMember("authorized"); } /** * Get the value of the '<code>authorized</code>' attribute. */ bool get_authorized() const { const Json::Value& storage = Storage("authorized"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>authorized</code>' attribute. * * Whether the app is authorized to access data on the user's Drive. * * @param[in] value The new value. */ void set_authorized(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("authorized")); } /** * Determine if the '<code>createInFolderTemplate</code>' attribute was set. * * @return true if the '<code>createInFolderTemplate</code>' attribute was * set. */ bool has_create_in_folder_template() const { return Storage().isMember("createInFolderTemplate"); } /** * Clears the '<code>createInFolderTemplate</code>' attribute. */ void clear_create_in_folder_template() { MutableStorage()->removeMember("createInFolderTemplate"); } /** * Get the value of the '<code>createInFolderTemplate</code>' attribute. */ const StringPiece get_create_in_folder_template() const { const Json::Value& v = Storage("createInFolderTemplate"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>createInFolderTemplate</code>' attribute. * * The template url to create a new file with this app in a given folder. The * template will contain {folderId} to be replaced by the folder to create the * new file in. * * @param[in] value The new value. */ void set_create_in_folder_template(const StringPiece& value) { *MutableStorage("createInFolderTemplate") = value.data(); } /** * Determine if the '<code>createUrl</code>' attribute was set. * * @return true if the '<code>createUrl</code>' attribute was set. */ bool has_create_url() const { return Storage().isMember("createUrl"); } /** * Clears the '<code>createUrl</code>' attribute. */ void clear_create_url() { MutableStorage()->removeMember("createUrl"); } /** * Get the value of the '<code>createUrl</code>' attribute. */ const StringPiece get_create_url() const { const Json::Value& v = Storage("createUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>createUrl</code>' attribute. * * The url to create a new file with this app. * * @param[in] value The new value. */ void set_create_url(const StringPiece& value) { *MutableStorage("createUrl") = value.data(); } /** * Determine if the '<code>hasDriveWideScope</code>' attribute was set. * * @return true if the '<code>hasDriveWideScope</code>' attribute was set. */ bool has_has_drive_wide_scope() const { return Storage().isMember("hasDriveWideScope"); } /** * Clears the '<code>hasDriveWideScope</code>' attribute. */ void clear_has_drive_wide_scope() { MutableStorage()->removeMember("hasDriveWideScope"); } /** * Get the value of the '<code>hasDriveWideScope</code>' attribute. */ bool get_has_drive_wide_scope() const { const Json::Value& storage = Storage("hasDriveWideScope"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>hasDriveWideScope</code>' attribute. * * Whether the app has drive-wide scope. An app with drive-wide scope can * access all files in the user's drive. * * @param[in] value The new value. */ void set_has_drive_wide_scope(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("hasDriveWideScope")); } /** * Determine if the '<code>icons</code>' attribute was set. * * @return true if the '<code>icons</code>' attribute was set. */ bool has_icons() const { return Storage().isMember("icons"); } /** * Clears the '<code>icons</code>' attribute. */ void clear_icons() { MutableStorage()->removeMember("icons"); } /** * Get a reference to the value of the '<code>icons</code>' attribute. */ const client::JsonCppArray<AppIcons > get_icons() const { const Json::Value& storage = Storage("icons"); return client::JsonValueToCppValueHelper<client::JsonCppArray<AppIcons > >(storage); } /** * Gets a reference to a mutable value of the '<code>icons</code>' property. * * The various icons for the app. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<AppIcons > mutable_icons() { Json::Value* storage = MutableStorage("icons"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<AppIcons > >(storage); } /** * Determine if the '<code>id</code>' attribute was set. * * @return true if the '<code>id</code>' attribute was set. */ bool has_id() const { return Storage().isMember("id"); } /** * Clears the '<code>id</code>' attribute. */ void clear_id() { MutableStorage()->removeMember("id"); } /** * Get the value of the '<code>id</code>' attribute. */ const StringPiece get_id() const { const Json::Value& v = Storage("id"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>id</code>' attribute. * * The ID of the app. * * @param[in] value The new value. */ void set_id(const StringPiece& value) { *MutableStorage("id") = value.data(); } /** * Determine if the '<code>installed</code>' attribute was set. * * @return true if the '<code>installed</code>' attribute was set. */ bool has_installed() const { return Storage().isMember("installed"); } /** * Clears the '<code>installed</code>' attribute. */ void clear_installed() { MutableStorage()->removeMember("installed"); } /** * Get the value of the '<code>installed</code>' attribute. */ bool get_installed() const { const Json::Value& storage = Storage("installed"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>installed</code>' attribute. * * Whether the app is installed. * * @param[in] value The new value. */ void set_installed(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("installed")); } /** * Determine if the '<code>kind</code>' attribute was set. * * @return true if the '<code>kind</code>' attribute was set. */ bool has_kind() const { return Storage().isMember("kind"); } /** * Clears the '<code>kind</code>' attribute. */ void clear_kind() { MutableStorage()->removeMember("kind"); } /** * Get the value of the '<code>kind</code>' attribute. */ const StringPiece get_kind() const { const Json::Value& v = Storage("kind"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kind</code>' attribute. * * This is always drive#app. * * @param[in] value The new value. */ void set_kind(const StringPiece& value) { *MutableStorage("kind") = value.data(); } /** * Determine if the '<code>longDescription</code>' attribute was set. * * @return true if the '<code>longDescription</code>' attribute was set. */ bool has_long_description() const { return Storage().isMember("longDescription"); } /** * Clears the '<code>longDescription</code>' attribute. */ void clear_long_description() { MutableStorage()->removeMember("longDescription"); } /** * Get the value of the '<code>longDescription</code>' attribute. */ const StringPiece get_long_description() const { const Json::Value& v = Storage("longDescription"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>longDescription</code>' attribute. * * A long description of the app. * * @param[in] value The new value. */ void set_long_description(const StringPiece& value) { *MutableStorage("longDescription") = value.data(); } /** * Determine if the '<code>name</code>' attribute was set. * * @return true if the '<code>name</code>' attribute was set. */ bool has_name() const { return Storage().isMember("name"); } /** * Clears the '<code>name</code>' attribute. */ void clear_name() { MutableStorage()->removeMember("name"); } /** * Get the value of the '<code>name</code>' attribute. */ const StringPiece get_name() const { const Json::Value& v = Storage("name"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>name</code>' attribute. * * The name of the app. * * @param[in] value The new value. */ void set_name(const StringPiece& value) { *MutableStorage("name") = value.data(); } /** * Determine if the '<code>objectType</code>' attribute was set. * * @return true if the '<code>objectType</code>' attribute was set. */ bool has_object_type() const { return Storage().isMember("objectType"); } /** * Clears the '<code>objectType</code>' attribute. */ void clear_object_type() { MutableStorage()->removeMember("objectType"); } /** * Get the value of the '<code>objectType</code>' attribute. */ const StringPiece get_object_type() const { const Json::Value& v = Storage("objectType"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>objectType</code>' attribute. * * The type of object this app creates (e.g. Chart). If empty, the app name * should be used instead. * * @param[in] value The new value. */ void set_object_type(const StringPiece& value) { *MutableStorage("objectType") = value.data(); } /** * Determine if the '<code>openUrlTemplate</code>' attribute was set. * * @return true if the '<code>openUrlTemplate</code>' attribute was set. */ bool has_open_url_template() const { return Storage().isMember("openUrlTemplate"); } /** * Clears the '<code>openUrlTemplate</code>' attribute. */ void clear_open_url_template() { MutableStorage()->removeMember("openUrlTemplate"); } /** * Get the value of the '<code>openUrlTemplate</code>' attribute. */ const StringPiece get_open_url_template() const { const Json::Value& v = Storage("openUrlTemplate"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>openUrlTemplate</code>' attribute. * * The template url for opening files with this app. The template will contain * {ids} and/or {exportIds} to be replaced by the actual file ids. See Open * Files for the full documentation. * * @param[in] value The new value. */ void set_open_url_template(const StringPiece& value) { *MutableStorage("openUrlTemplate") = value.data(); } /** * Determine if the '<code>primaryFileExtensions</code>' attribute was set. * * @return true if the '<code>primaryFileExtensions</code>' attribute was set. */ bool has_primary_file_extensions() const { return Storage().isMember("primaryFileExtensions"); } /** * Clears the '<code>primaryFileExtensions</code>' attribute. */ void clear_primary_file_extensions() { MutableStorage()->removeMember("primaryFileExtensions"); } /** * Get a reference to the value of the '<code>primaryFileExtensions</code>' * attribute. */ const client::JsonCppArray<string > get_primary_file_extensions() const { const Json::Value& storage = Storage("primaryFileExtensions"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the * '<code>primaryFileExtensions</code>' property. * * The list of primary file extensions. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_primaryFileExtensions() { Json::Value* storage = MutableStorage("primaryFileExtensions"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>primaryMimeTypes</code>' attribute was set. * * @return true if the '<code>primaryMimeTypes</code>' attribute was set. */ bool has_primary_mime_types() const { return Storage().isMember("primaryMimeTypes"); } /** * Clears the '<code>primaryMimeTypes</code>' attribute. */ void clear_primary_mime_types() { MutableStorage()->removeMember("primaryMimeTypes"); } /** * Get a reference to the value of the '<code>primaryMimeTypes</code>' * attribute. */ const client::JsonCppArray<string > get_primary_mime_types() const { const Json::Value& storage = Storage("primaryMimeTypes"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>primaryMimeTypes</code>' * property. * * The list of primary mime types. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_primaryMimeTypes() { Json::Value* storage = MutableStorage("primaryMimeTypes"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>productId</code>' attribute was set. * * @return true if the '<code>productId</code>' attribute was set. */ bool has_product_id() const { return Storage().isMember("productId"); } /** * Clears the '<code>productId</code>' attribute. */ void clear_product_id() { MutableStorage()->removeMember("productId"); } /** * Get the value of the '<code>productId</code>' attribute. */ const StringPiece get_product_id() const { const Json::Value& v = Storage("productId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>productId</code>' attribute. * * The ID of the product listing for this app. * * @param[in] value The new value. */ void set_product_id(const StringPiece& value) { *MutableStorage("productId") = value.data(); } /** * Determine if the '<code>productUrl</code>' attribute was set. * * @return true if the '<code>productUrl</code>' attribute was set. */ bool has_product_url() const { return Storage().isMember("productUrl"); } /** * Clears the '<code>productUrl</code>' attribute. */ void clear_product_url() { MutableStorage()->removeMember("productUrl"); } /** * Get the value of the '<code>productUrl</code>' attribute. */ const StringPiece get_product_url() const { const Json::Value& v = Storage("productUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>productUrl</code>' attribute. * * A link to the product listing for this app. * * @param[in] value The new value. */ void set_product_url(const StringPiece& value) { *MutableStorage("productUrl") = value.data(); } /** * Determine if the '<code>secondaryFileExtensions</code>' attribute was set. * * @return true if the '<code>secondaryFileExtensions</code>' attribute was * set. */ bool has_secondary_file_extensions() const { return Storage().isMember("secondaryFileExtensions"); } /** * Clears the '<code>secondaryFileExtensions</code>' attribute. */ void clear_secondary_file_extensions() { MutableStorage()->removeMember("secondaryFileExtensions"); } /** * Get a reference to the value of the '<code>secondaryFileExtensions</code>' * attribute. */ const client::JsonCppArray<string > get_secondary_file_extensions() const { const Json::Value& storage = Storage("secondaryFileExtensions"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the * '<code>secondaryFileExtensions</code>' property. * * The list of secondary file extensions. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_secondaryFileExtensions() { Json::Value* storage = MutableStorage("secondaryFileExtensions"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>secondaryMimeTypes</code>' attribute was set. * * @return true if the '<code>secondaryMimeTypes</code>' attribute was set. */ bool has_secondary_mime_types() const { return Storage().isMember("secondaryMimeTypes"); } /** * Clears the '<code>secondaryMimeTypes</code>' attribute. */ void clear_secondary_mime_types() { MutableStorage()->removeMember("secondaryMimeTypes"); } /** * Get a reference to the value of the '<code>secondaryMimeTypes</code>' * attribute. */ const client::JsonCppArray<string > get_secondary_mime_types() const { const Json::Value& storage = Storage("secondaryMimeTypes"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the * '<code>secondaryMimeTypes</code>' property. * * The list of secondary mime types. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_secondaryMimeTypes() { Json::Value* storage = MutableStorage("secondaryMimeTypes"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>shortDescription</code>' attribute was set. * * @return true if the '<code>shortDescription</code>' attribute was set. */ bool has_short_description() const { return Storage().isMember("shortDescription"); } /** * Clears the '<code>shortDescription</code>' attribute. */ void clear_short_description() { MutableStorage()->removeMember("shortDescription"); } /** * Get the value of the '<code>shortDescription</code>' attribute. */ const StringPiece get_short_description() const { const Json::Value& v = Storage("shortDescription"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>shortDescription</code>' attribute. * * A short description of the app. * * @param[in] value The new value. */ void set_short_description(const StringPiece& value) { *MutableStorage("shortDescription") = value.data(); } /** * Determine if the '<code>supportsCreate</code>' attribute was set. * * @return true if the '<code>supportsCreate</code>' attribute was set. */ bool has_supports_create() const { return Storage().isMember("supportsCreate"); } /** * Clears the '<code>supportsCreate</code>' attribute. */ void clear_supports_create() { MutableStorage()->removeMember("supportsCreate"); } /** * Get the value of the '<code>supportsCreate</code>' attribute. */ bool get_supports_create() const { const Json::Value& storage = Storage("supportsCreate"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>supportsCreate</code>' attribute. * * Whether this app supports creating new objects. * * @param[in] value The new value. */ void set_supports_create(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("supportsCreate")); } /** * Determine if the '<code>supportsImport</code>' attribute was set. * * @return true if the '<code>supportsImport</code>' attribute was set. */ bool has_supports_import() const { return Storage().isMember("supportsImport"); } /** * Clears the '<code>supportsImport</code>' attribute. */ void clear_supports_import() { MutableStorage()->removeMember("supportsImport"); } /** * Get the value of the '<code>supportsImport</code>' attribute. */ bool get_supports_import() const { const Json::Value& storage = Storage("supportsImport"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>supportsImport</code>' attribute. * * Whether this app supports importing Google Docs. * * @param[in] value The new value. */ void set_supports_import(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("supportsImport")); } /** * Determine if the '<code>supportsMultiOpen</code>' attribute was set. * * @return true if the '<code>supportsMultiOpen</code>' attribute was set. */ bool has_supports_multi_open() const { return Storage().isMember("supportsMultiOpen"); } /** * Clears the '<code>supportsMultiOpen</code>' attribute. */ void clear_supports_multi_open() { MutableStorage()->removeMember("supportsMultiOpen"); } /** * Get the value of the '<code>supportsMultiOpen</code>' attribute. */ bool get_supports_multi_open() const { const Json::Value& storage = Storage("supportsMultiOpen"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>supportsMultiOpen</code>' attribute. * * Whether this app supports opening more than one file. * * @param[in] value The new value. */ void set_supports_multi_open(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("supportsMultiOpen")); } /** * Determine if the '<code>supportsOfflineCreate</code>' attribute was set. * * @return true if the '<code>supportsOfflineCreate</code>' attribute was set. */ bool has_supports_offline_create() const { return Storage().isMember("supportsOfflineCreate"); } /** * Clears the '<code>supportsOfflineCreate</code>' attribute. */ void clear_supports_offline_create() { MutableStorage()->removeMember("supportsOfflineCreate"); } /** * Get the value of the '<code>supportsOfflineCreate</code>' attribute. */ bool get_supports_offline_create() const { const Json::Value& storage = Storage("supportsOfflineCreate"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>supportsOfflineCreate</code>' attribute. * * Whether this app supports creating new files when offline. * * @param[in] value The new value. */ void set_supports_offline_create(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("supportsOfflineCreate")); } /** * Determine if the '<code>useByDefault</code>' attribute was set. * * @return true if the '<code>useByDefault</code>' attribute was set. */ bool has_use_by_default() const { return Storage().isMember("useByDefault"); } /** * Clears the '<code>useByDefault</code>' attribute. */ void clear_use_by_default() { MutableStorage()->removeMember("useByDefault"); } /** * Get the value of the '<code>useByDefault</code>' attribute. */ bool get_use_by_default() const { const Json::Value& storage = Storage("useByDefault"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>useByDefault</code>' attribute. * * Whether the app is selected as the default handler for the types it * supports. * * @param[in] value The new value. */ void set_use_by_default(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("useByDefault")); } private: void operator=(const App&); }; // App } // namespace google_drive_api #endif // GOOGLE_DRIVE_API_APP_H_ <file_sep>/src/googleapis/client/util/mongoose_webserver.h /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #ifndef GOOGLEAPIS_UTIL_MONGOOSE_WEBSERVER_H_ #define GOOGLEAPIS_UTIL_MONGOOSE_WEBSERVER_H_ #include <map> #include "googleapis/client/util/abstract_webserver.h" #include "googleapis/client/util/status.h" #include "googleapis/base/callback.h" #include "googleapis/base/macros.h" #include <mongoose/mongoose.h> namespace googleapis { namespace client { /* * Provides a web server for samples and testing. * @ingroup PlatformLayerWebServer * * This class and the use of Mongoose Web Server available from * https://code.google.com/p/mongoose/ * * This class is currently only intended to support testing and tinkering. * It is not robust for production use. The underlying library is probably * sufficient, but this wrapper uses only minimal configuration and processing. */ class MongooseWebServer : public AbstractWebServer { public: static const char ACCESS_LOG_FILE[]; static const char DOCUMENT_ROOT[]; static const char ENABLE_KEEP_ALIVE[]; static const char ERROR_LOG_FILE[]; static const char LISTENING_PORTS[]; static const char NUM_THREADS[]; static const char REQUEST_TIMEOUT_MS[]; static const char SSL_CERTIFICATE[]; /* * Constructs an http server on the given port * * @param[in] port Should be non-0. */ explicit MongooseWebServer(int port); /* * Standard destructor. */ virtual ~MongooseWebServer(); /* * Determines whether we are using SSL or not. * @return if we'll use SSL (https). */ bool use_ssl() const { return !mongoose_option(kSslCertificateOption).empty(); } /* * Override Mongoose options. * * This replaces the old options that were overriden. * * @param[in] options The options will be copied. They must be set * before the server is started. */ void set_mongoose_options(const std::map<string, string>& options) { options_ = options; } /* * Returns Mongoose options that were overriden. */ const std::map<string, string>& mongoose_options() const { return options_; } /* * Clears Mongoose option overrides. */ void clear_mongoose_options() { options_.clear(); } /* * Explicitly configure an individual Mongoose server option. * * @param[in] name See the Mongoose Documentation for option names. * @param[in] value See the Mongoose Documentation for option values. */ void set_mongoose_option(const string& name, const string& value) { options_.insert(std::make_pair(name, value)); } /* * Returns value for individual option, or empty if not set. */ const string mongoose_option(const string& name) const { std::map<string, string>::const_iterator it = options_.find(name); if (it == options_.end()) return ""; return it->second; } /* * Clears an overiden Mongoose options back to the default value. */ void clear_mongoose_option(const string& name) { std::map<string, string>::iterator it = options_.find(name); if (it != options_.end()) { options_.erase(it); } } /* * Returns actual protocol depending on whether SSL was enabled. */ virtual string url_protocol() const; protected: /* * Starts the server. * * @return ok or reason for error. */ virtual googleapis::util::Status DoStartup(); /* * Stops the server. * * @return ok or reason for error. */ virtual void DoShutdown(); protected: /* * Sends the body response with the given http_code. * * @param[in] content_type The MIME content_type for the response. * @param[in] http_code The HTTP status code to return. * @param[in] body The HTTP body to return. * @param[in] connection The connection passed to the DoHandleUrl. */ int SendResponse( const string& content_type, int http_code, const string& body, struct mg_connection* connection); private: const string kSslCertificateOption; std::map<string, string> options_; struct mg_callbacks* callbacks_; struct mg_context* mg_context_; static int BeginRequestHandler(struct mg_connection* conn); DISALLOW_COPY_AND_ASSIGN(MongooseWebServer); }; } // namespace client } // namespace googleapis #endif // GOOGLEAPIS_UTIL_MONGOOSE_WEBSERVER_H_ <file_sep>/service_apis/youtube/google/youtube_api/access_policy.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_ACCESS_POLICY_H_ #define GOOGLE_YOUTUBE_API_ACCESS_POLICY_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Rights management policy for YouTube resources. * * @ingroup DataObject */ class AccessPolicy : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static AccessPolicy* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AccessPolicy(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AccessPolicy(Json::Value* storage); /** * Standard destructor. */ virtual ~AccessPolicy(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::AccessPolicy</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::AccessPolicy"); } /** * Determine if the '<code>allowed</code>' attribute was set. * * @return true if the '<code>allowed</code>' attribute was set. */ bool has_allowed() const { return Storage().isMember("allowed"); } /** * Clears the '<code>allowed</code>' attribute. */ void clear_allowed() { MutableStorage()->removeMember("allowed"); } /** * Get the value of the '<code>allowed</code>' attribute. */ bool get_allowed() const { const Json::Value& storage = Storage("allowed"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>allowed</code>' attribute. * * The value of allowed indicates whether the access to the policy is allowed * or denied by default. * * @param[in] value The new value. */ void set_allowed(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("allowed")); } /** * Determine if the '<code>exception</code>' attribute was set. * * @return true if the '<code>exception</code>' attribute was set. */ bool has_exception() const { return Storage().isMember("exception"); } /** * Clears the '<code>exception</code>' attribute. */ void clear_exception() { MutableStorage()->removeMember("exception"); } /** * Get a reference to the value of the '<code>exception</code>' attribute. */ const client::JsonCppArray<string > get_exception() const { const Json::Value& storage = Storage("exception"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>exception</code>' * property. * * A list of region codes that identify countries where the default policy do * not apply. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_exception() { Json::Value* storage = MutableStorage("exception"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } private: void operator=(const AccessPolicy&); }; // AccessPolicy } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_ACCESS_POLICY_H_ <file_sep>/src/googleapis/client/transport/http_request_batch.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <cstdio> #include <set> #include <vector> #include "googleapis/client/data/data_reader.h" #include "googleapis/client/data/data_writer.h" #include "googleapis/client/transport/http_authorization.h" #include "googleapis/client/transport/http_request.h" #include "googleapis/client/transport/http_request_batch.h" #include "googleapis/client/transport/http_scribe.h" #include "googleapis/client/transport/http_transport.h" #include "googleapis/client/util/status.h" #include "googleapis/strings/strcat.h" namespace googleapis { namespace client { #ifndef _WIN32 using std::snprintf; #endif // TODO(user): In batch request, we encode the pointer to the batch into the // request as an identifier, then in ExtractPartResponse we convert back to // an address. That is dangerous. Replace that scheme with something where // we do not blindly dereference user data. string HttpRequestBatch::PointerToHex(void *p) { char tmp[40]; // more than enough for 128 bit address snprintf(tmp, sizeof(tmp), "%p", p); return tmp; } namespace { // These are the requests that we'll make to be batched. // They are specialized to act as a specification for the batch to // form its multipart message rather than to actually be sent themselves. class IndividualRequest : public HttpRequest { public: IndividualRequest( HttpMethod method, HttpTransport* transport, HttpRequestCallback* callback) : HttpRequest(method, transport) { if (callback) { set_callback(callback); } } ~IndividualRequest() {} // Set the response from the multipart response entry for this request. void ParseResponse(const StringPiece& payload) { std::unique_ptr<DataReader> payload_reader( NewUnmanagedInMemoryDataReader(payload)); HttpTransport::ReadResponse(payload_reader.get(), this->response()); this->response()->set_body_reader( this->response()->body_writer()->NewUnmanagedDataReader()); } // Adds multipart body for this individual request, minus the boundary. void Encode(std::vector<DataReader*>* readers, std::vector<DataReader*>* destroy_later) { string* header_str = new string; std::unique_ptr<DataWriter> writer(NewStringDataWriter(header_str)); HttpTransport::WriteRequestPreamble(this, writer.get()); Closure* delete_str = DeletePointerClosure(header_str); DataReader* header_reader = writer->NewManagedDataReader(delete_str); readers->push_back(header_reader); destroy_later->push_back(header_reader); DataReader* content = content_reader(); if (content) { readers->push_back(content); } } protected: void DoExecute(HttpResponse* response) { mutable_state()->set_transport_status( StatusInternalError( "Elements in batch requests should not be executed individually")); } private: DISALLOW_COPY_AND_ASSIGN(IndividualRequest); }; // Helper function to get the next block in a multipart response. static StringPiece GetMultipartBlock( const StringPiece whole_response, // the mutipart response body int64 offset, // in whole_response where block begins const string& kBoundaryMarker, // for intermediary blocks const string& kLastBoundaryMarker, // for final block bool* processing_last, // true if we matched the last marker int64* next_offset) { // where next block after this begins *processing_last = false; int end_offset = whole_response.find(kBoundaryMarker, offset); if (end_offset == string::npos) { *processing_last = true; end_offset = whole_response.find(kLastBoundaryMarker, offset); } if (end_offset == string::npos) { *next_offset = string::npos; return ""; } *next_offset = end_offset + (*processing_last ? kLastBoundaryMarker.size() : kBoundaryMarker.size()); return whole_response.substr(offset, end_offset - offset); } // Given an indivdiual response, verify that it makes sense and identify // the original HttpRequest (our specialized IndividualRequest) that it is for. static googleapis::util::Status ExtractPartResponse( const StringPiece& multipart_block, std::set<HttpRequest*>* expected_requests, // remove the one we find. StringPiece* http_response_message, // subset of multipart_block on out IndividualRequest** http_request) { // request found or NULL http_response_message->clear(); *http_request = NULL; int double_eoln_offset = multipart_block.find(kCRLFCRLF); if (double_eoln_offset == StringPiece::npos) { return StatusUnknown( StrCat("Missing response part separator for batched message.")); } // +kCRLF to keep last eoln. int64 end_metadata = double_eoln_offset + kCRLF.size(); *http_response_message = multipart_block.substr( double_eoln_offset + kCRLFCRLF.size(), multipart_block.size() - double_eoln_offset - kCRLFCRLF.size()); string batch_metadata(multipart_block.data(), end_metadata); LowerString(&batch_metadata); if (batch_metadata.find("content-type: application/http\r\n") == string::npos) { return StatusUnknown("Missing or wrong batch part content-type"); } const char content_id_header_prefix[] = "content-id: <response-"; int64 id_header_offset = batch_metadata.find(content_id_header_prefix); if (id_header_offset == string::npos) { return StatusUnknown("Missing batch part content-id"); } void *id; int pointer_offset = id_header_offset + sizeof(content_id_header_prefix) - 1; if (sscanf(batch_metadata.c_str() + pointer_offset, "%p>\r\n", &id) != 1) { return StatusUnknown("content-id batch part was not as expected"); } // The id is an HttpRequest which is really our internal IndividualRequest // since that's how we encapsulate it. *http_request = reinterpret_cast<IndividualRequest*>(id); std::set<HttpRequest*>::iterator found = expected_requests->find( *http_request); if (found == expected_requests->end()) { *http_request = NULL; return StatusUnknown("Got unexpected content-id in batch response"); } expected_requests->erase(found); return StatusOk(); } static googleapis::util::Status ResolveResponses( const string& boundary_text, DataReader* reader, std::vector<HttpRequest*>* requests) { const string kBoundaryMarker = StrCat(kCRLF, "--", boundary_text, kCRLF); const string kLastBoundaryMarker = StrCat(kCRLF, "--", boundary_text, "--", kCRLF); string whole_response = reader->RemainderToString(); googleapis::util::Status return_status = StatusOk(); googleapis::util::Status transport_status = StatusOk(); if (!StringPiece(whole_response).starts_with( kBoundaryMarker.c_str() + kCRLF.size())) { transport_status = StatusUnknown( "Response does not begin with boundary marker"); return_status = transport_status; LOG(ERROR) << return_status.error_message(); } // Collect all the requests we expect to be in this batch. std::set<HttpRequest*> expected_requests; for (HttpRequestBatch::BatchedRequestList::iterator it = requests->begin(); it != requests->end(); ++it) { HttpRequestState* state = (*it)->mutable_state(); if (!transport_status.ok()) { state->set_transport_status(transport_status); } if (!state->transport_status().ok()) { // Was never sent, so just finish it now. state->AutoTransitionAndNotifyIfDone().IgnoreError(); } else { expected_requests.insert(*it); } } // Iterate over the parts in the response. // Resolve their content-id back to the original request // (we used the pointer address as the id). // We'll remove the requests as we resolve them so we can catch those // which never had a response, etc. int64 offset = kBoundaryMarker.size() - kCRLF.size(); int64 next_offset; bool processing_last = false; for (; !processing_last; offset = next_offset) { StringPiece this_multipart_block = GetMultipartBlock( whole_response, offset, kBoundaryMarker, kLastBoundaryMarker, &processing_last, &next_offset); if (next_offset == string::npos) { googleapis::util::Status status = StatusUnknown("Missing closing multipart boundary marker."); if (return_status.ok()) { return_status = status; LOG(ERROR) << status.error_message(); } else { VLOG(1) << status.error_message(); } break; } IndividualRequest* individual_request; StringPiece part_request_response_text; googleapis::util::Status status = ExtractPartResponse( this_multipart_block, &expected_requests, &part_request_response_text, &individual_request); if (!status.ok()) { if (return_status.ok()) { return_status = status; LOG(ERROR) << status.error_message(); } else { VLOG(1) << status.error_message(); } continue; } individual_request->ParseResponse(part_request_response_text); // TODO(user): 20130815 // Call error handler here when appropriate and add to followup batch on // retry. Post retries and chain another call to handle those batches // posting async if this was async. Chain the batch requests within this // structure so perhaps the caller can see if needed. HttpRequestState* state = individual_request->mutable_state(); state->AutoTransitionAndNotifyIfDone().IgnoreError(); } if (!expected_requests.empty()) { googleapis::util::Status missing_error = StatusUnknown("Never received response for batched request"); for (std::set<HttpRequest*>::iterator it = expected_requests.begin(); it != expected_requests.end(); ++it) { HttpRequestState* state = (*it)->mutable_state(); state->set_transport_status(missing_error); state->AutoTransitionAndNotifyIfDone().IgnoreError(); VLOG(1) << missing_error.error_message(); } // Keep the existing error since it might be the cause. // but if everything looked ok up to here then report this. if (return_status.ok()) { LOG(ERROR) << missing_error.error_message(); return_status = missing_error; } } return return_status; } const char DEFAULT_BATCH_REQUEST_URL[] = "https://www.googleapis.com/batch"; } // anonymous namespace HttpRequestBatch::HttpRequestBatch(HttpTransport* transport) : http_request_(transport->NewHttpRequest(HttpRequest::POST)), boundary_("bAtch bOundAry") { http_request_->set_url(DEFAULT_BATCH_REQUEST_URL); // If we are scribing a transcript then dont show the details of this // low level message because we'll already be showing the high level batch // message. This message wont be censored properly because of the multipart // nature to it. The HttpScribe interface knows about BatchHttpMessage so // can properly censor it as well as produce more readable transcripts for // it. We'll still leave the URL behind to help reconcile it. http_request_->set_scribe_restrictions(HttpScribe::MASK_NO_PAYLOADS); } HttpRequestBatch::~HttpRequestBatch() { Clear(); // In async mode, http_request_ is self-destructing. So to avoid double-free // we must release the unique_ptr. But be careful not to do that if the // request hasn't executed. if (http_request_->state().done()) { http_request_->DestroyWhenDone(); http_request_.release(); } } void HttpRequestBatch::Clear() { // clear all the requests so they are notified, but then delete them all // so this batch request is empty again. for (std::vector<HttpRequest*>::iterator it = requests_.begin(); it != requests_.end(); ++it) { (*it)->Clear(); delete *it; } requests_.clear(); } HttpRequest* HttpRequestBatch::NewHttpRequest( HttpRequest::HttpMethod method, HttpRequestCallback* callback) { HttpRequest* request = new IndividualRequest( method, http_request_->transport(), callback); requests_.push_back(request); return request; } util::Status HttpRequestBatch::RemoveAndDestroyRequest(HttpRequest* request) { for (std::vector<HttpRequest*>::iterator it = requests_.begin(); it != requests_.end(); ++it) { if (*it == request) { request->WillNotExecute(StatusAborted("Removing from batch")); delete *it; requests_.erase(it); return StatusOk(); } } return StatusInvalidArgument("Request not in batch"); } util::Status HttpRequestBatch::Execute() { PrepareFinalHttpRequest(); HttpScribe* scribe = http_request_->transport()->scribe(); if (scribe) { scribe->AboutToSendRequestBatch(this); } googleapis::util::Status status = http_request_->Execute(); ProcessHttpResponse(NULL, http_request_.get()); return batch_processing_status_; } void HttpRequestBatch::ExecuteAsync(HttpRequestCallback* callback) { HttpRequestCallback* batch_callback = NewCallback(this, &HttpRequestBatch::ProcessHttpResponse, callback); PrepareFinalHttpRequest(); HttpScribe* scribe = http_request_->transport()->scribe(); if (scribe) { scribe->AboutToSendRequestBatch(this); } http_request_->ExecuteAsync(batch_callback); } void HttpRequestBatch::PrepareFinalHttpRequest() { // The actual request will be a private request that is a normal request // (i.e. created from the transport originally bound to this one). // We'll form a multipart payload with a part for each of the requests // aggregated in this batch and copy all the top-level headers in that // were set on this. Then we'll execute the request and do similar copying // from the private response back into the response bound to this one. std::vector<DataReader*> individual_readers; std::vector<DataReader*>* readers_to_destroy = new std::vector<DataReader*>; for (std::vector<HttpRequest*>::const_iterator it = requests_.begin(); it != requests_.end(); ++it) { IndividualRequest* part = static_cast<IndividualRequest*>(*it); string* preamble = new string; StrAppend(preamble, "--", boundary_, kCRLF, "Content-Type: application/http", kCRLF, "Content-Transfer-Encoding: binary", kCRLF); StrAppend(preamble, "Content-ID: <", PointerToHex(*it), ">", kCRLFCRLF); DataReader* preamble_reader = NewManagedInMemoryDataReader(preamble); individual_readers.push_back(preamble_reader); readers_to_destroy->push_back(preamble_reader); // Authorize the http request if it had a credential. // Normally this happens in the HTTP's Execute method // but we are bypassing that. if (part->credential()) { googleapis::util::Status auth_status = part->credential()->AuthorizeRequest(part); if (!auth_status.ok()) { LOG(ERROR) << "Failed to authorize batched request: " << auth_status.error_message(); // We wont bother sending this request. We'll have to use // the Content-ID field in the metadata to line up responses // since cardinalities wont match anymore. part->mutable_state()->set_transport_status(auth_status); continue; } } part->Encode(&individual_readers, readers_to_destroy); } DataReader* last_terminator = NewManagedInMemoryDataReader(StrCat("--", boundary_, "--", kCRLF)); individual_readers.push_back(last_terminator); readers_to_destroy->push_back(last_terminator); http_request_->set_content_type( StrCat("multipart/mixed; boundary=\"", boundary_, "\"")); http_request_->set_content_reader( NewManagedCompositeDataReader( individual_readers, NewCompositeReaderListAndContainerDeleter(readers_to_destroy))); } static void ScribeResponseAndFinishCallback( HttpRequestBatch* batch, HttpRequestCallback* callback) { HttpRequest* http_request = batch->mutable_http_request(); HttpScribe* scribe = http_request->transport()->scribe(); if (scribe) { HttpResponse* response = http_request->response(); if (response->http_code()) { scribe->ReceivedResponseForRequestBatch(batch); } else { scribe->RequestBatchFailedWithTransportError( batch, response->transport_status()); } } if (callback) { callback->Run(http_request); } } void HttpRequestBatch::ProcessHttpResponse( HttpRequestCallback* callback, HttpRequest* expected_request) { AutoClosureRunner runner( NewCallback(&ScribeResponseAndFinishCallback, this, callback)); CHECK_EQ(http_request_.get(), expected_request); HttpResponse* response = expected_request->response(); if (!response->transport_status().ok()) { batch_processing_status_ = response->transport_status(); LOG(ERROR) << "Could not send batch request"; return; } const char kBoundaryMarker[] = "boundary="; HttpHeaderMultiMap::const_iterator found_content_type = response->headers().find(HttpRequest::HttpHeader_CONTENT_TYPE); const string kEmpty; const string& content_type = found_content_type == response->headers().end() ? kEmpty : found_content_type->second; int pos = content_type.find(kBoundaryMarker); if (pos == string::npos) { batch_processing_status_ = StatusUnknown( StrCat("Expected multipart content type: ", content_type)); return; } string kResponseBoundary = content_type.substr(pos + sizeof(kBoundaryMarker) - 1); batch_processing_status_ = ResolveResponses( kResponseBoundary, response->body_reader(), &requests_); if (!batch_processing_status_.ok()) { LOG(ERROR) << "Responses from server were not as expected: " << batch_processing_status_.error_message(); } } HttpRequest* HttpRequestBatch::AddFromGenericRequestAndRetire( HttpRequest* original, HttpRequestCallback* callback) { HttpRequest* part = NewHttpRequest(original->http_method()); original->SwapToRequestThenDestroy(part); if (callback) { part->set_callback(callback); } return part; } } // namespace client } // namespace googleapis <file_sep>/service_apis/youtube/google/youtube_api/video.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Description: // Supports core YouTube features, such as uploading videos, creating and managing playlists, searching for content, and much more. // Classes: // Video // Documentation: // https://developers.google.com/youtube/v3 #include "google/youtube_api/video.h" #include <string> #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/video_age_gating.h" #include "google/youtube_api/video_content_details.h" #include "google/youtube_api/video_file_details.h" #include "google/youtube_api/video_live_streaming_details.h" #include "google/youtube_api/video_localization.h" #include "google/youtube_api/video_monetization_details.h" #include "google/youtube_api/video_player.h" #include "google/youtube_api/video_processing_details.h" #include "google/youtube_api/video_project_details.h" #include "google/youtube_api/video_recording_details.h" #include "google/youtube_api/video_snippet.h" #include "google/youtube_api/video_statistics.h" #include "google/youtube_api/video_status.h" #include "google/youtube_api/video_suggestions.h" #include "google/youtube_api/video_topic_details.h" #include <string> #include "googleapis/strings/strcat.h" namespace google_youtube_api { using namespace googleapis; // Object factory method (static). Video* Video::New() { return new client::JsonCppCapsule<Video>; } // Standard immutable constructor. Video::Video(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. Video::Video(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. Video::~Video() { } // Properties. const VideoAgeGating Video::get_age_gating() const { const Json::Value& storage = Storage("ageGating"); return client::JsonValueToCppValueHelper<VideoAgeGating >(storage); } VideoAgeGating Video::mutable_ageGating() { Json::Value* storage = MutableStorage("ageGating"); return client::JsonValueToMutableCppValueHelper<VideoAgeGating >(storage); } const VideoContentDetails Video::get_content_details() const { const Json::Value& storage = Storage("contentDetails"); return client::JsonValueToCppValueHelper<VideoContentDetails >(storage); } VideoContentDetails Video::mutable_contentDetails() { Json::Value* storage = MutableStorage("contentDetails"); return client::JsonValueToMutableCppValueHelper<VideoContentDetails >(storage); } const VideoFileDetails Video::get_file_details() const { const Json::Value& storage = Storage("fileDetails"); return client::JsonValueToCppValueHelper<VideoFileDetails >(storage); } VideoFileDetails Video::mutable_fileDetails() { Json::Value* storage = MutableStorage("fileDetails"); return client::JsonValueToMutableCppValueHelper<VideoFileDetails >(storage); } const VideoLiveStreamingDetails Video::get_live_streaming_details() const { const Json::Value& storage = Storage("liveStreamingDetails"); return client::JsonValueToCppValueHelper<VideoLiveStreamingDetails >(storage); } VideoLiveStreamingDetails Video::mutable_liveStreamingDetails() { Json::Value* storage = MutableStorage("liveStreamingDetails"); return client::JsonValueToMutableCppValueHelper<VideoLiveStreamingDetails >(storage); } const client::JsonCppAssociativeArray<VideoLocalization > Video::get_localizations() const { const Json::Value& storage = Storage("localizations"); return client::JsonValueToCppValueHelper<client::JsonCppAssociativeArray<VideoLocalization > >(storage); } client::JsonCppAssociativeArray<VideoLocalization > Video::mutable_localizations() { Json::Value* storage = MutableStorage("localizations"); return client::JsonValueToMutableCppValueHelper<client::JsonCppAssociativeArray<VideoLocalization > >(storage); } const VideoMonetizationDetails Video::get_monetization_details() const { const Json::Value& storage = Storage("monetizationDetails"); return client::JsonValueToCppValueHelper<VideoMonetizationDetails >(storage); } VideoMonetizationDetails Video::mutable_monetizationDetails() { Json::Value* storage = MutableStorage("monetizationDetails"); return client::JsonValueToMutableCppValueHelper<VideoMonetizationDetails >(storage); } const VideoPlayer Video::get_player() const { const Json::Value& storage = Storage("player"); return client::JsonValueToCppValueHelper<VideoPlayer >(storage); } VideoPlayer Video::mutable_player() { Json::Value* storage = MutableStorage("player"); return client::JsonValueToMutableCppValueHelper<VideoPlayer >(storage); } const VideoProcessingDetails Video::get_processing_details() const { const Json::Value& storage = Storage("processingDetails"); return client::JsonValueToCppValueHelper<VideoProcessingDetails >(storage); } VideoProcessingDetails Video::mutable_processingDetails() { Json::Value* storage = MutableStorage("processingDetails"); return client::JsonValueToMutableCppValueHelper<VideoProcessingDetails >(storage); } const VideoProjectDetails Video::get_project_details() const { const Json::Value& storage = Storage("projectDetails"); return client::JsonValueToCppValueHelper<VideoProjectDetails >(storage); } VideoProjectDetails Video::mutable_projectDetails() { Json::Value* storage = MutableStorage("projectDetails"); return client::JsonValueToMutableCppValueHelper<VideoProjectDetails >(storage); } const VideoRecordingDetails Video::get_recording_details() const { const Json::Value& storage = Storage("recordingDetails"); return client::JsonValueToCppValueHelper<VideoRecordingDetails >(storage); } VideoRecordingDetails Video::mutable_recordingDetails() { Json::Value* storage = MutableStorage("recordingDetails"); return client::JsonValueToMutableCppValueHelper<VideoRecordingDetails >(storage); } const VideoSnippet Video::get_snippet() const { const Json::Value& storage = Storage("snippet"); return client::JsonValueToCppValueHelper<VideoSnippet >(storage); } VideoSnippet Video::mutable_snippet() { Json::Value* storage = MutableStorage("snippet"); return client::JsonValueToMutableCppValueHelper<VideoSnippet >(storage); } const VideoStatistics Video::get_statistics() const { const Json::Value& storage = Storage("statistics"); return client::JsonValueToCppValueHelper<VideoStatistics >(storage); } VideoStatistics Video::mutable_statistics() { Json::Value* storage = MutableStorage("statistics"); return client::JsonValueToMutableCppValueHelper<VideoStatistics >(storage); } const VideoStatus Video::get_status() const { const Json::Value& storage = Storage("status"); return client::JsonValueToCppValueHelper<VideoStatus >(storage); } VideoStatus Video::mutable_status() { Json::Value* storage = MutableStorage("status"); return client::JsonValueToMutableCppValueHelper<VideoStatus >(storage); } const VideoSuggestions Video::get_suggestions() const { const Json::Value& storage = Storage("suggestions"); return client::JsonValueToCppValueHelper<VideoSuggestions >(storage); } VideoSuggestions Video::mutable_suggestions() { Json::Value* storage = MutableStorage("suggestions"); return client::JsonValueToMutableCppValueHelper<VideoSuggestions >(storage); } const VideoTopicDetails Video::get_topic_details() const { const Json::Value& storage = Storage("topicDetails"); return client::JsonValueToCppValueHelper<VideoTopicDetails >(storage); } VideoTopicDetails Video::mutable_topicDetails() { Json::Value* storage = MutableStorage("topicDetails"); return client::JsonValueToMutableCppValueHelper<VideoTopicDetails >(storage); } } // namespace google_youtube_api <file_sep>/service_apis/youtube/google/youtube_api/caption_snippet.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_CAPTION_SNIPPET_H_ #define GOOGLE_YOUTUBE_API_CAPTION_SNIPPET_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Basic details about a caption track, such as its language and name. * * @ingroup DataObject */ class CaptionSnippet : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static CaptionSnippet* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit CaptionSnippet(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit CaptionSnippet(Json::Value* storage); /** * Standard destructor. */ virtual ~CaptionSnippet(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::CaptionSnippet</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::CaptionSnippet"); } /** * Determine if the '<code>audioTrackType</code>' attribute was set. * * @return true if the '<code>audioTrackType</code>' attribute was set. */ bool has_audio_track_type() const { return Storage().isMember("audioTrackType"); } /** * Clears the '<code>audioTrackType</code>' attribute. */ void clear_audio_track_type() { MutableStorage()->removeMember("audioTrackType"); } /** * Get the value of the '<code>audioTrackType</code>' attribute. */ const StringPiece get_audio_track_type() const { const Json::Value& v = Storage("audioTrackType"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>audioTrackType</code>' attribute. * * The type of audio track associated with the caption track. * * @param[in] value The new value. */ void set_audio_track_type(const StringPiece& value) { *MutableStorage("audioTrackType") = value.data(); } /** * Determine if the '<code>failureReason</code>' attribute was set. * * @return true if the '<code>failureReason</code>' attribute was set. */ bool has_failure_reason() const { return Storage().isMember("failureReason"); } /** * Clears the '<code>failureReason</code>' attribute. */ void clear_failure_reason() { MutableStorage()->removeMember("failureReason"); } /** * Get the value of the '<code>failureReason</code>' attribute. */ const StringPiece get_failure_reason() const { const Json::Value& v = Storage("failureReason"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>failureReason</code>' attribute. * * The reason that YouTube failed to process the caption track. This property * is only present if the state property's value is failed. * * @param[in] value The new value. */ void set_failure_reason(const StringPiece& value) { *MutableStorage("failureReason") = value.data(); } /** * Determine if the '<code>isAutoSynced</code>' attribute was set. * * @return true if the '<code>isAutoSynced</code>' attribute was set. */ bool has_is_auto_synced() const { return Storage().isMember("isAutoSynced"); } /** * Clears the '<code>isAutoSynced</code>' attribute. */ void clear_is_auto_synced() { MutableStorage()->removeMember("isAutoSynced"); } /** * Get the value of the '<code>isAutoSynced</code>' attribute. */ bool get_is_auto_synced() const { const Json::Value& storage = Storage("isAutoSynced"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>isAutoSynced</code>' attribute. * * Indicates whether YouTube synchronized the caption track to the audio track * in the video. The value will be true if a sync was explicitly requested * when the caption track was uploaded. For example, when calling the * captions.insert or captions.update methods, you can set the sync parameter * to true to instruct YouTube to sync the uploaded track to the video. If the * value is false, YouTube uses the time codes in the uploaded caption track * to determine when to display captions. * * @param[in] value The new value. */ void set_is_auto_synced(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("isAutoSynced")); } /** * Determine if the '<code>isCC</code>' attribute was set. * * @return true if the '<code>isCC</code>' attribute was set. */ bool has_is_cc() const { return Storage().isMember("isCC"); } /** * Clears the '<code>isCC</code>' attribute. */ void clear_is_cc() { MutableStorage()->removeMember("isCC"); } /** * Get the value of the '<code>isCC</code>' attribute. */ bool get_is_cc() const { const Json::Value& storage = Storage("isCC"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>isCC</code>' attribute. * * Indicates whether the track contains closed captions for the deaf and hard * of hearing. The default value is false. * * @param[in] value The new value. */ void set_is_cc(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("isCC")); } /** * Determine if the '<code>isDraft</code>' attribute was set. * * @return true if the '<code>isDraft</code>' attribute was set. */ bool has_is_draft() const { return Storage().isMember("isDraft"); } /** * Clears the '<code>isDraft</code>' attribute. */ void clear_is_draft() { MutableStorage()->removeMember("isDraft"); } /** * Get the value of the '<code>isDraft</code>' attribute. */ bool get_is_draft() const { const Json::Value& storage = Storage("isDraft"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>isDraft</code>' attribute. * * Indicates whether the caption track is a draft. If the value is true, then * the track is not publicly visible. The default value is false. * * @param[in] value The new value. */ void set_is_draft(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("isDraft")); } /** * Determine if the '<code>isEasyReader</code>' attribute was set. * * @return true if the '<code>isEasyReader</code>' attribute was set. */ bool has_is_easy_reader() const { return Storage().isMember("isEasyReader"); } /** * Clears the '<code>isEasyReader</code>' attribute. */ void clear_is_easy_reader() { MutableStorage()->removeMember("isEasyReader"); } /** * Get the value of the '<code>isEasyReader</code>' attribute. */ bool get_is_easy_reader() const { const Json::Value& storage = Storage("isEasyReader"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>isEasyReader</code>' attribute. * * Indicates whether caption track is formatted for "easy reader," meaning it * is at a third-grade level for language learners. The default value is * false. * * @param[in] value The new value. */ void set_is_easy_reader(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("isEasyReader")); } /** * Determine if the '<code>isLarge</code>' attribute was set. * * @return true if the '<code>isLarge</code>' attribute was set. */ bool has_is_large() const { return Storage().isMember("isLarge"); } /** * Clears the '<code>isLarge</code>' attribute. */ void clear_is_large() { MutableStorage()->removeMember("isLarge"); } /** * Get the value of the '<code>isLarge</code>' attribute. */ bool get_is_large() const { const Json::Value& storage = Storage("isLarge"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>isLarge</code>' attribute. * * Indicates whether the caption track uses large text for the vision- * impaired. The default value is false. * * @param[in] value The new value. */ void set_is_large(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("isLarge")); } /** * Determine if the '<code>language</code>' attribute was set. * * @return true if the '<code>language</code>' attribute was set. */ bool has_language() const { return Storage().isMember("language"); } /** * Clears the '<code>language</code>' attribute. */ void clear_language() { MutableStorage()->removeMember("language"); } /** * Get the value of the '<code>language</code>' attribute. */ const StringPiece get_language() const { const Json::Value& v = Storage("language"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>language</code>' attribute. * * The language of the caption track. The property value is a BCP-47 language * tag. * * @param[in] value The new value. */ void set_language(const StringPiece& value) { *MutableStorage("language") = value.data(); } /** * Determine if the '<code>lastUpdated</code>' attribute was set. * * @return true if the '<code>lastUpdated</code>' attribute was set. */ bool has_last_updated() const { return Storage().isMember("lastUpdated"); } /** * Clears the '<code>lastUpdated</code>' attribute. */ void clear_last_updated() { MutableStorage()->removeMember("lastUpdated"); } /** * Get the value of the '<code>lastUpdated</code>' attribute. */ client::DateTime get_last_updated() const { const Json::Value& storage = Storage("lastUpdated"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>lastUpdated</code>' attribute. * * The date and time when the caption track was last updated. The value is * specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. * * @param[in] value The new value. */ void set_last_updated(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("lastUpdated")); } /** * Determine if the '<code>name</code>' attribute was set. * * @return true if the '<code>name</code>' attribute was set. */ bool has_name() const { return Storage().isMember("name"); } /** * Clears the '<code>name</code>' attribute. */ void clear_name() { MutableStorage()->removeMember("name"); } /** * Get the value of the '<code>name</code>' attribute. */ const StringPiece get_name() const { const Json::Value& v = Storage("name"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>name</code>' attribute. * * The name of the caption track. The name is intended to be visible to the * user as an option during playback. * * @param[in] value The new value. */ void set_name(const StringPiece& value) { *MutableStorage("name") = value.data(); } /** * Determine if the '<code>status</code>' attribute was set. * * @return true if the '<code>status</code>' attribute was set. */ bool has_status() const { return Storage().isMember("status"); } /** * Clears the '<code>status</code>' attribute. */ void clear_status() { MutableStorage()->removeMember("status"); } /** * Get the value of the '<code>status</code>' attribute. */ const StringPiece get_status() const { const Json::Value& v = Storage("status"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>status</code>' attribute. * * The caption track's status. * * @param[in] value The new value. */ void set_status(const StringPiece& value) { *MutableStorage("status") = value.data(); } /** * Determine if the '<code>trackKind</code>' attribute was set. * * @return true if the '<code>trackKind</code>' attribute was set. */ bool has_track_kind() const { return Storage().isMember("trackKind"); } /** * Clears the '<code>trackKind</code>' attribute. */ void clear_track_kind() { MutableStorage()->removeMember("trackKind"); } /** * Get the value of the '<code>trackKind</code>' attribute. */ const StringPiece get_track_kind() const { const Json::Value& v = Storage("trackKind"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>trackKind</code>' attribute. * * The caption track's type. * * @param[in] value The new value. */ void set_track_kind(const StringPiece& value) { *MutableStorage("trackKind") = value.data(); } /** * Determine if the '<code>videoId</code>' attribute was set. * * @return true if the '<code>videoId</code>' attribute was set. */ bool has_video_id() const { return Storage().isMember("videoId"); } /** * Clears the '<code>videoId</code>' attribute. */ void clear_video_id() { MutableStorage()->removeMember("videoId"); } /** * Get the value of the '<code>videoId</code>' attribute. */ const StringPiece get_video_id() const { const Json::Value& v = Storage("videoId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>videoId</code>' attribute. * * The ID that YouTube uses to uniquely identify the video associated with the * caption track. * * @param[in] value The new value. */ void set_video_id(const StringPiece& value) { *MutableStorage("videoId") = value.data(); } private: void operator=(const CaptionSnippet&); }; // CaptionSnippet } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_CAPTION_SNIPPET_H_ <file_sep>/service_apis/youtube/google/youtube_api/live_chat_message_snippet.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Description: // Supports core YouTube features, such as uploading videos, creating and managing playlists, searching for content, and much more. // Classes: // LiveChatMessageSnippet // Documentation: // https://developers.google.com/youtube/v3 #include "google/youtube_api/live_chat_message_snippet.h" #include <string> #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/live_chat_fan_funding_event_details.h" #include "google/youtube_api/live_chat_message_deleted_details.h" #include "google/youtube_api/live_chat_message_retracted_details.h" #include "google/youtube_api/live_chat_poll_closed_details.h" #include "google/youtube_api/live_chat_poll_edited_details.h" #include "google/youtube_api/live_chat_poll_opened_details.h" #include "google/youtube_api/live_chat_poll_voted_details.h" #include "google/youtube_api/live_chat_super_chat_details.h" #include "google/youtube_api/live_chat_text_message_details.h" #include "google/youtube_api/live_chat_user_banned_message_details.h" #include <string> #include "googleapis/strings/strcat.h" namespace google_youtube_api { using namespace googleapis; // Object factory method (static). LiveChatMessageSnippet* LiveChatMessageSnippet::New() { return new client::JsonCppCapsule<LiveChatMessageSnippet>; } // Standard immutable constructor. LiveChatMessageSnippet::LiveChatMessageSnippet(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. LiveChatMessageSnippet::LiveChatMessageSnippet(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. LiveChatMessageSnippet::~LiveChatMessageSnippet() { } // Properties. const LiveChatFanFundingEventDetails LiveChatMessageSnippet::get_fan_funding_event_details() const { const Json::Value& storage = Storage("fanFundingEventDetails"); return client::JsonValueToCppValueHelper<LiveChatFanFundingEventDetails >(storage); } LiveChatFanFundingEventDetails LiveChatMessageSnippet::mutable_fanFundingEventDetails() { Json::Value* storage = MutableStorage("fanFundingEventDetails"); return client::JsonValueToMutableCppValueHelper<LiveChatFanFundingEventDetails >(storage); } const LiveChatMessageDeletedDetails LiveChatMessageSnippet::get_message_deleted_details() const { const Json::Value& storage = Storage("messageDeletedDetails"); return client::JsonValueToCppValueHelper<LiveChatMessageDeletedDetails >(storage); } LiveChatMessageDeletedDetails LiveChatMessageSnippet::mutable_messageDeletedDetails() { Json::Value* storage = MutableStorage("messageDeletedDetails"); return client::JsonValueToMutableCppValueHelper<LiveChatMessageDeletedDetails >(storage); } const LiveChatMessageRetractedDetails LiveChatMessageSnippet::get_message_retracted_details() const { const Json::Value& storage = Storage("messageRetractedDetails"); return client::JsonValueToCppValueHelper<LiveChatMessageRetractedDetails >(storage); } LiveChatMessageRetractedDetails LiveChatMessageSnippet::mutable_messageRetractedDetails() { Json::Value* storage = MutableStorage("messageRetractedDetails"); return client::JsonValueToMutableCppValueHelper<LiveChatMessageRetractedDetails >(storage); } const LiveChatPollClosedDetails LiveChatMessageSnippet::get_poll_closed_details() const { const Json::Value& storage = Storage("pollClosedDetails"); return client::JsonValueToCppValueHelper<LiveChatPollClosedDetails >(storage); } LiveChatPollClosedDetails LiveChatMessageSnippet::mutable_pollClosedDetails() { Json::Value* storage = MutableStorage("pollClosedDetails"); return client::JsonValueToMutableCppValueHelper<LiveChatPollClosedDetails >(storage); } const LiveChatPollEditedDetails LiveChatMessageSnippet::get_poll_edited_details() const { const Json::Value& storage = Storage("pollEditedDetails"); return client::JsonValueToCppValueHelper<LiveChatPollEditedDetails >(storage); } LiveChatPollEditedDetails LiveChatMessageSnippet::mutable_pollEditedDetails() { Json::Value* storage = MutableStorage("pollEditedDetails"); return client::JsonValueToMutableCppValueHelper<LiveChatPollEditedDetails >(storage); } const LiveChatPollOpenedDetails LiveChatMessageSnippet::get_poll_opened_details() const { const Json::Value& storage = Storage("pollOpenedDetails"); return client::JsonValueToCppValueHelper<LiveChatPollOpenedDetails >(storage); } LiveChatPollOpenedDetails LiveChatMessageSnippet::mutable_pollOpenedDetails() { Json::Value* storage = MutableStorage("pollOpenedDetails"); return client::JsonValueToMutableCppValueHelper<LiveChatPollOpenedDetails >(storage); } const LiveChatPollVotedDetails LiveChatMessageSnippet::get_poll_voted_details() const { const Json::Value& storage = Storage("pollVotedDetails"); return client::JsonValueToCppValueHelper<LiveChatPollVotedDetails >(storage); } LiveChatPollVotedDetails LiveChatMessageSnippet::mutable_pollVotedDetails() { Json::Value* storage = MutableStorage("pollVotedDetails"); return client::JsonValueToMutableCppValueHelper<LiveChatPollVotedDetails >(storage); } const LiveChatSuperChatDetails LiveChatMessageSnippet::get_super_chat_details() const { const Json::Value& storage = Storage("superChatDetails"); return client::JsonValueToCppValueHelper<LiveChatSuperChatDetails >(storage); } LiveChatSuperChatDetails LiveChatMessageSnippet::mutable_superChatDetails() { Json::Value* storage = MutableStorage("superChatDetails"); return client::JsonValueToMutableCppValueHelper<LiveChatSuperChatDetails >(storage); } const LiveChatTextMessageDetails LiveChatMessageSnippet::get_text_message_details() const { const Json::Value& storage = Storage("textMessageDetails"); return client::JsonValueToCppValueHelper<LiveChatTextMessageDetails >(storage); } LiveChatTextMessageDetails LiveChatMessageSnippet::mutable_textMessageDetails() { Json::Value* storage = MutableStorage("textMessageDetails"); return client::JsonValueToMutableCppValueHelper<LiveChatTextMessageDetails >(storage); } const LiveChatUserBannedMessageDetails LiveChatMessageSnippet::get_user_banned_details() const { const Json::Value& storage = Storage("userBannedDetails"); return client::JsonValueToCppValueHelper<LiveChatUserBannedMessageDetails >(storage); } LiveChatUserBannedMessageDetails LiveChatMessageSnippet::mutable_userBannedDetails() { Json::Value* storage = MutableStorage("userBannedDetails"); return client::JsonValueToMutableCppValueHelper<LiveChatUserBannedMessageDetails >(storage); } } // namespace google_youtube_api <file_sep>/service_apis/youtube/google/youtube_api/live_broadcast_status.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_LIVE_BROADCAST_STATUS_H_ #define GOOGLE_YOUTUBE_API_LIVE_BROADCAST_STATUS_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * No description provided. * * @ingroup DataObject */ class LiveBroadcastStatus : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static LiveBroadcastStatus* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveBroadcastStatus(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveBroadcastStatus(Json::Value* storage); /** * Standard destructor. */ virtual ~LiveBroadcastStatus(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::LiveBroadcastStatus</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::LiveBroadcastStatus"); } /** * Determine if the '<code>lifeCycleStatus</code>' attribute was set. * * @return true if the '<code>lifeCycleStatus</code>' attribute was set. */ bool has_life_cycle_status() const { return Storage().isMember("lifeCycleStatus"); } /** * Clears the '<code>lifeCycleStatus</code>' attribute. */ void clear_life_cycle_status() { MutableStorage()->removeMember("lifeCycleStatus"); } /** * Get the value of the '<code>lifeCycleStatus</code>' attribute. */ const StringPiece get_life_cycle_status() const { const Json::Value& v = Storage("lifeCycleStatus"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>lifeCycleStatus</code>' attribute. * * The broadcast's status. The status can be updated using the API's * liveBroadcasts.transition method. * * @param[in] value The new value. */ void set_life_cycle_status(const StringPiece& value) { *MutableStorage("lifeCycleStatus") = value.data(); } /** * Determine if the '<code>liveBroadcastPriority</code>' attribute was set. * * @return true if the '<code>liveBroadcastPriority</code>' attribute was set. */ bool has_live_broadcast_priority() const { return Storage().isMember("liveBroadcastPriority"); } /** * Clears the '<code>liveBroadcastPriority</code>' attribute. */ void clear_live_broadcast_priority() { MutableStorage()->removeMember("liveBroadcastPriority"); } /** * Get the value of the '<code>liveBroadcastPriority</code>' attribute. */ const StringPiece get_live_broadcast_priority() const { const Json::Value& v = Storage("liveBroadcastPriority"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>liveBroadcastPriority</code>' attribute. * * Priority of the live broadcast event (internal state). * * @param[in] value The new value. */ void set_live_broadcast_priority(const StringPiece& value) { *MutableStorage("liveBroadcastPriority") = value.data(); } /** * Determine if the '<code>privacyStatus</code>' attribute was set. * * @return true if the '<code>privacyStatus</code>' attribute was set. */ bool has_privacy_status() const { return Storage().isMember("privacyStatus"); } /** * Clears the '<code>privacyStatus</code>' attribute. */ void clear_privacy_status() { MutableStorage()->removeMember("privacyStatus"); } /** * Get the value of the '<code>privacyStatus</code>' attribute. */ const StringPiece get_privacy_status() const { const Json::Value& v = Storage("privacyStatus"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>privacyStatus</code>' attribute. * * The broadcast's privacy status. Note that the broadcast represents exactly * one YouTube video, so the privacy settings are identical to those supported * for videos. In addition, you can set this field by modifying the broadcast * resource or by setting the privacyStatus field of the corresponding video * resource. * * @param[in] value The new value. */ void set_privacy_status(const StringPiece& value) { *MutableStorage("privacyStatus") = value.data(); } /** * Determine if the '<code>recordingStatus</code>' attribute was set. * * @return true if the '<code>recordingStatus</code>' attribute was set. */ bool has_recording_status() const { return Storage().isMember("recordingStatus"); } /** * Clears the '<code>recordingStatus</code>' attribute. */ void clear_recording_status() { MutableStorage()->removeMember("recordingStatus"); } /** * Get the value of the '<code>recordingStatus</code>' attribute. */ const StringPiece get_recording_status() const { const Json::Value& v = Storage("recordingStatus"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>recordingStatus</code>' attribute. * * The broadcast's recording status. * * @param[in] value The new value. */ void set_recording_status(const StringPiece& value) { *MutableStorage("recordingStatus") = value.data(); } private: void operator=(const LiveBroadcastStatus&); }; // LiveBroadcastStatus } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_LIVE_BROADCAST_STATUS_H_ <file_sep>/service_apis/youtube/google/youtube_api/channel_content_details.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_CHANNEL_CONTENT_DETAILS_H_ #define GOOGLE_YOUTUBE_API_CHANNEL_CONTENT_DETAILS_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Details about the content of a channel. * * @ingroup DataObject */ class ChannelContentDetails : public client::JsonCppData { public: /** * No description provided. * * @ingroup DataObject */ class ChannelContentDetailsRelatedPlaylists : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static ChannelContentDetailsRelatedPlaylists* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelContentDetailsRelatedPlaylists(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelContentDetailsRelatedPlaylists(Json::Value* storage); /** * Standard destructor. */ virtual ~ChannelContentDetailsRelatedPlaylists(); /** * Returns a string denoting the type of this data object. * * @return * <code>google_youtube_api::ChannelContentDetailsRelatedPlaylists</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::ChannelContentDetailsRelatedPlaylists"); } /** * Determine if the '<code>favorites</code>' attribute was set. * * @return true if the '<code>favorites</code>' attribute was set. */ bool has_favorites() const { return Storage().isMember("favorites"); } /** * Clears the '<code>favorites</code>' attribute. */ void clear_favorites() { MutableStorage()->removeMember("favorites"); } /** * Get the value of the '<code>favorites</code>' attribute. */ const StringPiece get_favorites() const { const Json::Value& v = Storage("favorites"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>favorites</code>' attribute. * * The ID of the playlist that contains the channel"s favorite videos. Use * the playlistItems.insert and playlistItems.delete to add or remove * items from that list. * * @param[in] value The new value. */ void set_favorites(const StringPiece& value) { *MutableStorage("favorites") = value.data(); } /** * Determine if the '<code>likes</code>' attribute was set. * * @return true if the '<code>likes</code>' attribute was set. */ bool has_likes() const { return Storage().isMember("likes"); } /** * Clears the '<code>likes</code>' attribute. */ void clear_likes() { MutableStorage()->removeMember("likes"); } /** * Get the value of the '<code>likes</code>' attribute. */ const StringPiece get_likes() const { const Json::Value& v = Storage("likes"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>likes</code>' attribute. * * The ID of the playlist that contains the channel"s liked videos. Use the * playlistItems.insert and playlistItems.delete to add or remove items * from that list. * * @param[in] value The new value. */ void set_likes(const StringPiece& value) { *MutableStorage("likes") = value.data(); } /** * Determine if the '<code>uploads</code>' attribute was set. * * @return true if the '<code>uploads</code>' attribute was set. */ bool has_uploads() const { return Storage().isMember("uploads"); } /** * Clears the '<code>uploads</code>' attribute. */ void clear_uploads() { MutableStorage()->removeMember("uploads"); } /** * Get the value of the '<code>uploads</code>' attribute. */ const StringPiece get_uploads() const { const Json::Value& v = Storage("uploads"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>uploads</code>' attribute. * * The ID of the playlist that contains the channel"s uploaded videos. Use * the videos.insert method to upload new videos and the videos.delete * method to delete previously uploaded videos. * * @param[in] value The new value. */ void set_uploads(const StringPiece& value) { *MutableStorage("uploads") = value.data(); } /** * Determine if the '<code>watchHistory</code>' attribute was set. * * @return true if the '<code>watchHistory</code>' attribute was set. */ bool has_watch_history() const { return Storage().isMember("watchHistory"); } /** * Clears the '<code>watchHistory</code>' attribute. */ void clear_watch_history() { MutableStorage()->removeMember("watchHistory"); } /** * Get the value of the '<code>watchHistory</code>' attribute. */ const StringPiece get_watch_history() const { const Json::Value& v = Storage("watchHistory"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>watchHistory</code>' attribute. * * The ID of the playlist that contains the channel"s watch history. Use the * playlistItems.insert and playlistItems.delete to add or remove items * from that list. * * @param[in] value The new value. */ void set_watch_history(const StringPiece& value) { *MutableStorage("watchHistory") = value.data(); } /** * Determine if the '<code>watchLater</code>' attribute was set. * * @return true if the '<code>watchLater</code>' attribute was set. */ bool has_watch_later() const { return Storage().isMember("watchLater"); } /** * Clears the '<code>watchLater</code>' attribute. */ void clear_watch_later() { MutableStorage()->removeMember("watchLater"); } /** * Get the value of the '<code>watchLater</code>' attribute. */ const StringPiece get_watch_later() const { const Json::Value& v = Storage("watchLater"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>watchLater</code>' attribute. * * The ID of the playlist that contains the channel"s watch later playlist. * Use the playlistItems.insert and playlistItems.delete to add or remove * items from that list. * * @param[in] value The new value. */ void set_watch_later(const StringPiece& value) { *MutableStorage("watchLater") = value.data(); } private: void operator=(const ChannelContentDetailsRelatedPlaylists&); }; // ChannelContentDetailsRelatedPlaylists /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static ChannelContentDetails* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelContentDetails(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelContentDetails(Json::Value* storage); /** * Standard destructor. */ virtual ~ChannelContentDetails(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::ChannelContentDetails</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::ChannelContentDetails"); } /** * Determine if the '<code>relatedPlaylists</code>' attribute was set. * * @return true if the '<code>relatedPlaylists</code>' attribute was set. */ bool has_related_playlists() const { return Storage().isMember("relatedPlaylists"); } /** * Clears the '<code>relatedPlaylists</code>' attribute. */ void clear_related_playlists() { MutableStorage()->removeMember("relatedPlaylists"); } /** * Get a reference to the value of the '<code>relatedPlaylists</code>' * attribute. */ const ChannelContentDetailsRelatedPlaylists get_related_playlists() const { const Json::Value& storage = Storage("relatedPlaylists"); return client::JsonValueToCppValueHelper<ChannelContentDetailsRelatedPlaylists >(storage); } /** * Gets a reference to a mutable value of the '<code>relatedPlaylists</code>' * property. * @return The result can be modified to change the attribute value. */ ChannelContentDetailsRelatedPlaylists mutable_relatedPlaylists() { Json::Value* storage = MutableStorage("relatedPlaylists"); return client::JsonValueToMutableCppValueHelper<ChannelContentDetailsRelatedPlaylists >(storage); } private: void operator=(const ChannelContentDetails&); }; // ChannelContentDetails } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_CHANNEL_CONTENT_DETAILS_H_ <file_sep>/service_apis/youtube/google/youtube_api/channel.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Description: // Supports core YouTube features, such as uploading videos, creating and managing playlists, searching for content, and much more. // Classes: // Channel // Documentation: // https://developers.google.com/youtube/v3 #include "google/youtube_api/channel.h" #include <string> #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/channel_audit_details.h" #include "google/youtube_api/channel_branding_settings.h" #include "google/youtube_api/channel_content_details.h" #include "google/youtube_api/channel_content_owner_details.h" #include "google/youtube_api/channel_conversion_pings.h" #include "google/youtube_api/channel_localization.h" #include "google/youtube_api/channel_snippet.h" #include "google/youtube_api/channel_statistics.h" #include "google/youtube_api/channel_status.h" #include "google/youtube_api/channel_topic_details.h" #include "google/youtube_api/invideo_promotion.h" #include <string> #include "googleapis/strings/strcat.h" namespace google_youtube_api { using namespace googleapis; // Object factory method (static). Channel* Channel::New() { return new client::JsonCppCapsule<Channel>; } // Standard immutable constructor. Channel::Channel(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. Channel::Channel(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. Channel::~Channel() { } // Properties. const ChannelAuditDetails Channel::get_audit_details() const { const Json::Value& storage = Storage("auditDetails"); return client::JsonValueToCppValueHelper<ChannelAuditDetails >(storage); } ChannelAuditDetails Channel::mutable_auditDetails() { Json::Value* storage = MutableStorage("auditDetails"); return client::JsonValueToMutableCppValueHelper<ChannelAuditDetails >(storage); } const ChannelBrandingSettings Channel::get_branding_settings() const { const Json::Value& storage = Storage("brandingSettings"); return client::JsonValueToCppValueHelper<ChannelBrandingSettings >(storage); } ChannelBrandingSettings Channel::mutable_brandingSettings() { Json::Value* storage = MutableStorage("brandingSettings"); return client::JsonValueToMutableCppValueHelper<ChannelBrandingSettings >(storage); } const ChannelContentDetails Channel::get_content_details() const { const Json::Value& storage = Storage("contentDetails"); return client::JsonValueToCppValueHelper<ChannelContentDetails >(storage); } ChannelContentDetails Channel::mutable_contentDetails() { Json::Value* storage = MutableStorage("contentDetails"); return client::JsonValueToMutableCppValueHelper<ChannelContentDetails >(storage); } const ChannelContentOwnerDetails Channel::get_content_owner_details() const { const Json::Value& storage = Storage("contentOwnerDetails"); return client::JsonValueToCppValueHelper<ChannelContentOwnerDetails >(storage); } ChannelContentOwnerDetails Channel::mutable_contentOwnerDetails() { Json::Value* storage = MutableStorage("contentOwnerDetails"); return client::JsonValueToMutableCppValueHelper<ChannelContentOwnerDetails >(storage); } const ChannelConversionPings Channel::get_conversion_pings() const { const Json::Value& storage = Storage("conversionPings"); return client::JsonValueToCppValueHelper<ChannelConversionPings >(storage); } ChannelConversionPings Channel::mutable_conversionPings() { Json::Value* storage = MutableStorage("conversionPings"); return client::JsonValueToMutableCppValueHelper<ChannelConversionPings >(storage); } const InvideoPromotion Channel::get_invideo_promotion() const { const Json::Value& storage = Storage("invideoPromotion"); return client::JsonValueToCppValueHelper<InvideoPromotion >(storage); } InvideoPromotion Channel::mutable_invideoPromotion() { Json::Value* storage = MutableStorage("invideoPromotion"); return client::JsonValueToMutableCppValueHelper<InvideoPromotion >(storage); } const client::JsonCppAssociativeArray<ChannelLocalization > Channel::get_localizations() const { const Json::Value& storage = Storage("localizations"); return client::JsonValueToCppValueHelper<client::JsonCppAssociativeArray<ChannelLocalization > >(storage); } client::JsonCppAssociativeArray<ChannelLocalization > Channel::mutable_localizations() { Json::Value* storage = MutableStorage("localizations"); return client::JsonValueToMutableCppValueHelper<client::JsonCppAssociativeArray<ChannelLocalization > >(storage); } const ChannelSnippet Channel::get_snippet() const { const Json::Value& storage = Storage("snippet"); return client::JsonValueToCppValueHelper<ChannelSnippet >(storage); } ChannelSnippet Channel::mutable_snippet() { Json::Value* storage = MutableStorage("snippet"); return client::JsonValueToMutableCppValueHelper<ChannelSnippet >(storage); } const ChannelStatistics Channel::get_statistics() const { const Json::Value& storage = Storage("statistics"); return client::JsonValueToCppValueHelper<ChannelStatistics >(storage); } ChannelStatistics Channel::mutable_statistics() { Json::Value* storage = MutableStorage("statistics"); return client::JsonValueToMutableCppValueHelper<ChannelStatistics >(storage); } const ChannelStatus Channel::get_status() const { const Json::Value& storage = Storage("status"); return client::JsonValueToCppValueHelper<ChannelStatus >(storage); } ChannelStatus Channel::mutable_status() { Json::Value* storage = MutableStorage("status"); return client::JsonValueToMutableCppValueHelper<ChannelStatus >(storage); } const ChannelTopicDetails Channel::get_topic_details() const { const Json::Value& storage = Storage("topicDetails"); return client::JsonValueToCppValueHelper<ChannelTopicDetails >(storage); } ChannelTopicDetails Channel::mutable_topicDetails() { Json::Value* storage = MutableStorage("topicDetails"); return client::JsonValueToMutableCppValueHelper<ChannelTopicDetails >(storage); } } // namespace google_youtube_api <file_sep>/service_apis/drive/google/drive_api/file.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Drive API (drive/v2) // Description: // Manages files in Drive including uploading, downloading, searching, detecting changes, and updating sharing permissions. // Classes: // File // Documentation: // https://developers.google.com/drive/ #include "google/drive_api/file.h" #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/drive_api/parent_reference.h" #include "google/drive_api/permission.h" #include "google/drive_api/property.h" #include "google/drive_api/user.h" #include <string> #include "googleapis/strings/strcat.h" namespace google_drive_api { using namespace googleapis; // Object factory method (static). File::FileCapabilities* File::FileCapabilities::New() { return new client::JsonCppCapsule<FileCapabilities>; } // Standard immutable constructor. File::FileCapabilities::FileCapabilities(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. File::FileCapabilities::FileCapabilities(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. File::FileCapabilities::~FileCapabilities() { } // Properties. // Object factory method (static). File::FileImageMediaMetadata::FileImageMediaMetadataLocation* File::FileImageMediaMetadata::FileImageMediaMetadataLocation::New() { return new client::JsonCppCapsule<FileImageMediaMetadataLocation>; } // Standard immutable constructor. File::FileImageMediaMetadata::FileImageMediaMetadataLocation::FileImageMediaMetadataLocation(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. File::FileImageMediaMetadata::FileImageMediaMetadataLocation::FileImageMediaMetadataLocation(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. File::FileImageMediaMetadata::FileImageMediaMetadataLocation::~FileImageMediaMetadataLocation() { } // Properties. // Object factory method (static). File::FileImageMediaMetadata* File::FileImageMediaMetadata::New() { return new client::JsonCppCapsule<FileImageMediaMetadata>; } // Standard immutable constructor. File::FileImageMediaMetadata::FileImageMediaMetadata(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. File::FileImageMediaMetadata::FileImageMediaMetadata(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. File::FileImageMediaMetadata::~FileImageMediaMetadata() { } // Properties. // Object factory method (static). File::FileIndexableText* File::FileIndexableText::New() { return new client::JsonCppCapsule<FileIndexableText>; } // Standard immutable constructor. File::FileIndexableText::FileIndexableText(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. File::FileIndexableText::FileIndexableText(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. File::FileIndexableText::~FileIndexableText() { } // Properties. // Object factory method (static). File::FileLabels* File::FileLabels::New() { return new client::JsonCppCapsule<FileLabels>; } // Standard immutable constructor. File::FileLabels::FileLabels(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. File::FileLabels::FileLabels(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. File::FileLabels::~FileLabels() { } // Properties. // Object factory method (static). File::FileThumbnail* File::FileThumbnail::New() { return new client::JsonCppCapsule<FileThumbnail>; } // Standard immutable constructor. File::FileThumbnail::FileThumbnail(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. File::FileThumbnail::FileThumbnail(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. File::FileThumbnail::~FileThumbnail() { } // Properties. // Object factory method (static). File::FileVideoMediaMetadata* File::FileVideoMediaMetadata::New() { return new client::JsonCppCapsule<FileVideoMediaMetadata>; } // Standard immutable constructor. File::FileVideoMediaMetadata::FileVideoMediaMetadata(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. File::FileVideoMediaMetadata::FileVideoMediaMetadata(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. File::FileVideoMediaMetadata::~FileVideoMediaMetadata() { } // Properties. // Object factory method (static). File* File::New() { return new client::JsonCppCapsule<File>; } // Standard immutable constructor. File::File(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. File::File(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. File::~File() { } // Properties. const User File::get_last_modifying_user() const { const Json::Value& storage = Storage("lastModifyingUser"); return client::JsonValueToCppValueHelper<User >(storage); } User File::mutable_lastModifyingUser() { Json::Value* storage = MutableStorage("lastModifyingUser"); return client::JsonValueToMutableCppValueHelper<User >(storage); } const client::JsonCppArray<User > File::get_owners() const { const Json::Value& storage = Storage("owners"); return client::JsonValueToCppValueHelper<client::JsonCppArray<User > >(storage); } client::JsonCppArray<User > File::mutable_owners() { Json::Value* storage = MutableStorage("owners"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<User > >(storage); } const client::JsonCppArray<ParentReference > File::get_parents() const { const Json::Value& storage = Storage("parents"); return client::JsonValueToCppValueHelper<client::JsonCppArray<ParentReference > >(storage); } client::JsonCppArray<ParentReference > File::mutable_parents() { Json::Value* storage = MutableStorage("parents"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<ParentReference > >(storage); } const client::JsonCppArray<Permission > File::get_permissions() const { const Json::Value& storage = Storage("permissions"); return client::JsonValueToCppValueHelper<client::JsonCppArray<Permission > >(storage); } client::JsonCppArray<Permission > File::mutable_permissions() { Json::Value* storage = MutableStorage("permissions"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<Permission > >(storage); } const client::JsonCppArray<Property > File::get_properties() const { const Json::Value& storage = Storage("properties"); return client::JsonValueToCppValueHelper<client::JsonCppArray<Property > >(storage); } client::JsonCppArray<Property > File::mutable_properties() { Json::Value* storage = MutableStorage("properties"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<Property > >(storage); } const User File::get_sharing_user() const { const Json::Value& storage = Storage("sharingUser"); return client::JsonValueToCppValueHelper<User >(storage); } User File::mutable_sharingUser() { Json::Value* storage = MutableStorage("sharingUser"); return client::JsonValueToMutableCppValueHelper<User >(storage); } const User File::get_trashing_user() const { const Json::Value& storage = Storage("trashingUser"); return client::JsonValueToCppValueHelper<User >(storage); } User File::mutable_trashingUser() { Json::Value* storage = MutableStorage("trashingUser"); return client::JsonValueToMutableCppValueHelper<User >(storage); } const Permission File::get_user_permission() const { const Json::Value& storage = Storage("userPermission"); return client::JsonValueToCppValueHelper<Permission >(storage); } Permission File::mutable_userPermission() { Json::Value* storage = MutableStorage("userPermission"); return client::JsonValueToMutableCppValueHelper<Permission >(storage); } } // namespace google_drive_api <file_sep>/service_apis/drive/CMakeLists.txt # This is a CMake file for Drive API v2 # using the Google APIs Client Library for C++. # # See http://google.github.io/google-api-cpp-client/latest/start/get_started # for more information about what to do with this file. project (drive) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/.) add_subdirectory(google/drive_api) <file_sep>/service_apis/drive/google/drive_api/comment_reply.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Drive API (drive/v2) // Generated from: // Version: v2 // Revision: 20170512 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_DRIVE_API_COMMENT_REPLY_H_ #define GOOGLE_DRIVE_API_COMMENT_REPLY_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/drive_api/user.h" namespace Json { class Value; } // namespace Json namespace google_drive_api { using namespace googleapis; /** * A comment on a file in Google Drive. * * @ingroup DataObject */ class CommentReply : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static CommentReply* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit CommentReply(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit CommentReply(Json::Value* storage); /** * Standard destructor. */ virtual ~CommentReply(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::CommentReply</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::CommentReply"); } /** * Determine if the '<code>author</code>' attribute was set. * * @return true if the '<code>author</code>' attribute was set. */ bool has_author() const { return Storage().isMember("author"); } /** * Clears the '<code>author</code>' attribute. */ void clear_author() { MutableStorage()->removeMember("author"); } /** * Get a reference to the value of the '<code>author</code>' attribute. */ const User get_author() const; /** * Gets a reference to a mutable value of the '<code>author</code>' property. * * The user who wrote this reply. * * @return The result can be modified to change the attribute value. */ User mutable_author(); /** * Determine if the '<code>content</code>' attribute was set. * * @return true if the '<code>content</code>' attribute was set. */ bool has_content() const { return Storage().isMember("content"); } /** * Clears the '<code>content</code>' attribute. */ void clear_content() { MutableStorage()->removeMember("content"); } /** * Get the value of the '<code>content</code>' attribute. */ const StringPiece get_content() const { const Json::Value& v = Storage("content"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>content</code>' attribute. * * The plain text content used to create this reply. This is not HTML safe and * should only be used as a starting point to make edits to a reply's content. * This field is required on inserts if no verb is specified (resolve/reopen). * * @param[in] value The new value. */ void set_content(const StringPiece& value) { *MutableStorage("content") = value.data(); } /** * Determine if the '<code>createdDate</code>' attribute was set. * * @return true if the '<code>createdDate</code>' attribute was set. */ bool has_created_date() const { return Storage().isMember("createdDate"); } /** * Clears the '<code>createdDate</code>' attribute. */ void clear_created_date() { MutableStorage()->removeMember("createdDate"); } /** * Get the value of the '<code>createdDate</code>' attribute. */ client::DateTime get_created_date() const { const Json::Value& storage = Storage("createdDate"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>createdDate</code>' attribute. * * The date when this reply was first created. * * @param[in] value The new value. */ void set_created_date(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("createdDate")); } /** * Determine if the '<code>deleted</code>' attribute was set. * * @return true if the '<code>deleted</code>' attribute was set. */ bool has_deleted() const { return Storage().isMember("deleted"); } /** * Clears the '<code>deleted</code>' attribute. */ void clear_deleted() { MutableStorage()->removeMember("deleted"); } /** * Get the value of the '<code>deleted</code>' attribute. */ bool get_deleted() const { const Json::Value& storage = Storage("deleted"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>deleted</code>' attribute. * * Whether this reply has been deleted. If a reply has been deleted the * content will be cleared and this will only represent a reply that once * existed. * * @param[in] value The new value. */ void set_deleted(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("deleted")); } /** * Determine if the '<code>htmlContent</code>' attribute was set. * * @return true if the '<code>htmlContent</code>' attribute was set. */ bool has_html_content() const { return Storage().isMember("htmlContent"); } /** * Clears the '<code>htmlContent</code>' attribute. */ void clear_html_content() { MutableStorage()->removeMember("htmlContent"); } /** * Get the value of the '<code>htmlContent</code>' attribute. */ const StringPiece get_html_content() const { const Json::Value& v = Storage("htmlContent"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>htmlContent</code>' attribute. * * HTML formatted content for this reply. * * @param[in] value The new value. */ void set_html_content(const StringPiece& value) { *MutableStorage("htmlContent") = value.data(); } /** * Determine if the '<code>kind</code>' attribute was set. * * @return true if the '<code>kind</code>' attribute was set. */ bool has_kind() const { return Storage().isMember("kind"); } /** * Clears the '<code>kind</code>' attribute. */ void clear_kind() { MutableStorage()->removeMember("kind"); } /** * Get the value of the '<code>kind</code>' attribute. */ const StringPiece get_kind() const { const Json::Value& v = Storage("kind"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kind</code>' attribute. * * This is always drive#commentReply. * * @param[in] value The new value. */ void set_kind(const StringPiece& value) { *MutableStorage("kind") = value.data(); } /** * Determine if the '<code>modifiedDate</code>' attribute was set. * * @return true if the '<code>modifiedDate</code>' attribute was set. */ bool has_modified_date() const { return Storage().isMember("modifiedDate"); } /** * Clears the '<code>modifiedDate</code>' attribute. */ void clear_modified_date() { MutableStorage()->removeMember("modifiedDate"); } /** * Get the value of the '<code>modifiedDate</code>' attribute. */ client::DateTime get_modified_date() const { const Json::Value& storage = Storage("modifiedDate"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>modifiedDate</code>' attribute. * * The date when this reply was last modified. * * @param[in] value The new value. */ void set_modified_date(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("modifiedDate")); } /** * Determine if the '<code>replyId</code>' attribute was set. * * @return true if the '<code>replyId</code>' attribute was set. */ bool has_reply_id() const { return Storage().isMember("replyId"); } /** * Clears the '<code>replyId</code>' attribute. */ void clear_reply_id() { MutableStorage()->removeMember("replyId"); } /** * Get the value of the '<code>replyId</code>' attribute. */ const StringPiece get_reply_id() const { const Json::Value& v = Storage("replyId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>replyId</code>' attribute. * * The ID of the reply. * * @param[in] value The new value. */ void set_reply_id(const StringPiece& value) { *MutableStorage("replyId") = value.data(); } /** * Determine if the '<code>verb</code>' attribute was set. * * @return true if the '<code>verb</code>' attribute was set. */ bool has_verb() const { return Storage().isMember("verb"); } /** * Clears the '<code>verb</code>' attribute. */ void clear_verb() { MutableStorage()->removeMember("verb"); } /** * Get the value of the '<code>verb</code>' attribute. */ const StringPiece get_verb() const { const Json::Value& v = Storage("verb"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>verb</code>' attribute. * * The action this reply performed to the parent comment. When creating a new * reply this is the action to be perform to the parent comment. Possible * values are: * <dl> * <dt>"resolve" * <dd>To resolve a comment. * <dt>"reopen" * <dd>To reopen (un-resolve) a comment. * </dl> * * * @param[in] value The new value. */ void set_verb(const StringPiece& value) { *MutableStorage("verb") = value.data(); } private: void operator=(const CommentReply&); }; // CommentReply } // namespace google_drive_api #endif // GOOGLE_DRIVE_API_COMMENT_REPLY_H_ <file_sep>/service_apis/drive/google/drive_api/team_drive.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Drive API (drive/v2) // Generated from: // Version: v2 // Revision: 20170512 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_DRIVE_API_TEAM_DRIVE_H_ #define GOOGLE_DRIVE_API_TEAM_DRIVE_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_drive_api { using namespace googleapis; /** * Representation of a Team Drive. * * @ingroup DataObject */ class TeamDrive : public client::JsonCppData { public: /** * An image file and cropping parameters from which a background image for * this Team Drive is set. This is a write only field; it can only be set on * drive.teamdrives.update requests that don't set themeId. When specified, * all fields of the backgroundImageFile must be set. * * @ingroup DataObject */ class TeamDriveBackgroundImageFile : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static TeamDriveBackgroundImageFile* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit TeamDriveBackgroundImageFile(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit TeamDriveBackgroundImageFile(Json::Value* storage); /** * Standard destructor. */ virtual ~TeamDriveBackgroundImageFile(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::TeamDriveBackgroundImageFile</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::TeamDriveBackgroundImageFile"); } /** * Determine if the '<code>id</code>' attribute was set. * * @return true if the '<code>id</code>' attribute was set. */ bool has_id() const { return Storage().isMember("id"); } /** * Clears the '<code>id</code>' attribute. */ void clear_id() { MutableStorage()->removeMember("id"); } /** * Get the value of the '<code>id</code>' attribute. */ const StringPiece get_id() const { const Json::Value& v = Storage("id"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>id</code>' attribute. * * The ID of an image file in Drive to use for the background image. * * @param[in] value The new value. */ void set_id(const StringPiece& value) { *MutableStorage("id") = value.data(); } /** * Determine if the '<code>width</code>' attribute was set. * * @return true if the '<code>width</code>' attribute was set. */ bool has_width() const { return Storage().isMember("width"); } /** * Clears the '<code>width</code>' attribute. */ void clear_width() { MutableStorage()->removeMember("width"); } /** * Get the value of the '<code>width</code>' attribute. */ float get_width() const { const Json::Value& storage = Storage("width"); return client::JsonValueToCppValueHelper<float >(storage); } /** * Change the '<code>width</code>' attribute. * * The width of the cropped image in the closed range of 0 to 1. This value * represents the width of the cropped image divided by the width of the * entire image. The height is computed by applying a width to height aspect * ratio of 80 to 9. The resulting image must be at least 1280 pixels wide * and 144 pixels high. * * @param[in] value The new value. */ void set_width(float value) { client::SetJsonValueFromCppValueHelper<float >( value, MutableStorage("width")); } /** * Determine if the '<code>xCoordinate</code>' attribute was set. * * @return true if the '<code>xCoordinate</code>' attribute was set. */ bool has_x_coordinate() const { return Storage().isMember("xCoordinate"); } /** * Clears the '<code>xCoordinate</code>' attribute. */ void clear_x_coordinate() { MutableStorage()->removeMember("xCoordinate"); } /** * Get the value of the '<code>xCoordinate</code>' attribute. */ float get_x_coordinate() const { const Json::Value& storage = Storage("xCoordinate"); return client::JsonValueToCppValueHelper<float >(storage); } /** * Change the '<code>xCoordinate</code>' attribute. * * The X coordinate of the upper left corner of the cropping area in the * background image. This is a value in the closed range of 0 to 1. This * value represents the horizontal distance from the left side of the entire * image to the left side of the cropping area divided by the width of the * entire image. * * @param[in] value The new value. */ void set_x_coordinate(float value) { client::SetJsonValueFromCppValueHelper<float >( value, MutableStorage("xCoordinate")); } /** * Determine if the '<code>yCoordinate</code>' attribute was set. * * @return true if the '<code>yCoordinate</code>' attribute was set. */ bool has_y_coordinate() const { return Storage().isMember("yCoordinate"); } /** * Clears the '<code>yCoordinate</code>' attribute. */ void clear_y_coordinate() { MutableStorage()->removeMember("yCoordinate"); } /** * Get the value of the '<code>yCoordinate</code>' attribute. */ float get_y_coordinate() const { const Json::Value& storage = Storage("yCoordinate"); return client::JsonValueToCppValueHelper<float >(storage); } /** * Change the '<code>yCoordinate</code>' attribute. * * The Y coordinate of the upper left corner of the cropping area in the * background image. This is a value in the closed range of 0 to 1. This * value represents the vertical distance from the top side of the entire * image to the top side of the cropping area divided by the height of the * entire image. * * @param[in] value The new value. */ void set_y_coordinate(float value) { client::SetJsonValueFromCppValueHelper<float >( value, MutableStorage("yCoordinate")); } private: void operator=(const TeamDriveBackgroundImageFile&); }; // TeamDriveBackgroundImageFile /** * Capabilities the current user has on this Team Drive. * * @ingroup DataObject */ class TeamDriveCapabilities : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static TeamDriveCapabilities* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit TeamDriveCapabilities(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit TeamDriveCapabilities(Json::Value* storage); /** * Standard destructor. */ virtual ~TeamDriveCapabilities(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::TeamDriveCapabilities</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::TeamDriveCapabilities"); } /** * Determine if the '<code>canAddChildren</code>' attribute was set. * * @return true if the '<code>canAddChildren</code>' attribute was set. */ bool has_can_add_children() const { return Storage().isMember("canAddChildren"); } /** * Clears the '<code>canAddChildren</code>' attribute. */ void clear_can_add_children() { MutableStorage()->removeMember("canAddChildren"); } /** * Get the value of the '<code>canAddChildren</code>' attribute. */ bool get_can_add_children() const { const Json::Value& storage = Storage("canAddChildren"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canAddChildren</code>' attribute. * * Whether the current user can add children to folders in this Team Drive. * * @param[in] value The new value. */ void set_can_add_children(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canAddChildren")); } /** * Determine if the '<code>canChangeTeamDriveBackground</code>' attribute * was set. * * @return true if the '<code>canChangeTeamDriveBackground</code>' attribute * was set. */ bool has_can_change_team_drive_background() const { return Storage().isMember("canChangeTeamDriveBackground"); } /** * Clears the '<code>canChangeTeamDriveBackground</code>' attribute. */ void clear_can_change_team_drive_background() { MutableStorage()->removeMember("canChangeTeamDriveBackground"); } /** * Get the value of the '<code>canChangeTeamDriveBackground</code>' * attribute. */ bool get_can_change_team_drive_background() const { const Json::Value& storage = Storage("canChangeTeamDriveBackground"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canChangeTeamDriveBackground</code>' attribute. * * Whether the current user can change the background of this Team Drive. * * @param[in] value The new value. */ void set_can_change_team_drive_background(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canChangeTeamDriveBackground")); } /** * Determine if the '<code>canComment</code>' attribute was set. * * @return true if the '<code>canComment</code>' attribute was set. */ bool has_can_comment() const { return Storage().isMember("canComment"); } /** * Clears the '<code>canComment</code>' attribute. */ void clear_can_comment() { MutableStorage()->removeMember("canComment"); } /** * Get the value of the '<code>canComment</code>' attribute. */ bool get_can_comment() const { const Json::Value& storage = Storage("canComment"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canComment</code>' attribute. * * Whether the current user can comment on files in this Team Drive. * * @param[in] value The new value. */ void set_can_comment(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canComment")); } /** * Determine if the '<code>canCopy</code>' attribute was set. * * @return true if the '<code>canCopy</code>' attribute was set. */ bool has_can_copy() const { return Storage().isMember("canCopy"); } /** * Clears the '<code>canCopy</code>' attribute. */ void clear_can_copy() { MutableStorage()->removeMember("canCopy"); } /** * Get the value of the '<code>canCopy</code>' attribute. */ bool get_can_copy() const { const Json::Value& storage = Storage("canCopy"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canCopy</code>' attribute. * * Whether the current user can copy files in this Team Drive. * * @param[in] value The new value. */ void set_can_copy(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canCopy")); } /** * Determine if the '<code>canDeleteTeamDrive</code>' attribute was set. * * @return true if the '<code>canDeleteTeamDrive</code>' attribute was set. */ bool has_can_delete_team_drive() const { return Storage().isMember("canDeleteTeamDrive"); } /** * Clears the '<code>canDeleteTeamDrive</code>' attribute. */ void clear_can_delete_team_drive() { MutableStorage()->removeMember("canDeleteTeamDrive"); } /** * Get the value of the '<code>canDeleteTeamDrive</code>' attribute. */ bool get_can_delete_team_drive() const { const Json::Value& storage = Storage("canDeleteTeamDrive"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canDeleteTeamDrive</code>' attribute. * * Whether the current user can delete this Team Drive. Attempting to delete * the Team Drive may still fail if there are untrashed items inside the * Team Drive. * * @param[in] value The new value. */ void set_can_delete_team_drive(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canDeleteTeamDrive")); } /** * Determine if the '<code>canDownload</code>' attribute was set. * * @return true if the '<code>canDownload</code>' attribute was set. */ bool has_can_download() const { return Storage().isMember("canDownload"); } /** * Clears the '<code>canDownload</code>' attribute. */ void clear_can_download() { MutableStorage()->removeMember("canDownload"); } /** * Get the value of the '<code>canDownload</code>' attribute. */ bool get_can_download() const { const Json::Value& storage = Storage("canDownload"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canDownload</code>' attribute. * * Whether the current user can download files in this Team Drive. * * @param[in] value The new value. */ void set_can_download(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canDownload")); } /** * Determine if the '<code>canEdit</code>' attribute was set. * * @return true if the '<code>canEdit</code>' attribute was set. */ bool has_can_edit() const { return Storage().isMember("canEdit"); } /** * Clears the '<code>canEdit</code>' attribute. */ void clear_can_edit() { MutableStorage()->removeMember("canEdit"); } /** * Get the value of the '<code>canEdit</code>' attribute. */ bool get_can_edit() const { const Json::Value& storage = Storage("canEdit"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canEdit</code>' attribute. * * Whether the current user can edit files in this Team Drive. * * @param[in] value The new value. */ void set_can_edit(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canEdit")); } /** * Determine if the '<code>canListChildren</code>' attribute was set. * * @return true if the '<code>canListChildren</code>' attribute was set. */ bool has_can_list_children() const { return Storage().isMember("canListChildren"); } /** * Clears the '<code>canListChildren</code>' attribute. */ void clear_can_list_children() { MutableStorage()->removeMember("canListChildren"); } /** * Get the value of the '<code>canListChildren</code>' attribute. */ bool get_can_list_children() const { const Json::Value& storage = Storage("canListChildren"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canListChildren</code>' attribute. * * Whether the current user can list the children of folders in this Team * Drive. * * @param[in] value The new value. */ void set_can_list_children(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canListChildren")); } /** * Determine if the '<code>canManageMembers</code>' attribute was set. * * @return true if the '<code>canManageMembers</code>' attribute was set. */ bool has_can_manage_members() const { return Storage().isMember("canManageMembers"); } /** * Clears the '<code>canManageMembers</code>' attribute. */ void clear_can_manage_members() { MutableStorage()->removeMember("canManageMembers"); } /** * Get the value of the '<code>canManageMembers</code>' attribute. */ bool get_can_manage_members() const { const Json::Value& storage = Storage("canManageMembers"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canManageMembers</code>' attribute. * * Whether the current user can add members to this Team Drive or remove * them or change their role. * * @param[in] value The new value. */ void set_can_manage_members(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canManageMembers")); } /** * Determine if the '<code>canReadRevisions</code>' attribute was set. * * @return true if the '<code>canReadRevisions</code>' attribute was set. */ bool has_can_read_revisions() const { return Storage().isMember("canReadRevisions"); } /** * Clears the '<code>canReadRevisions</code>' attribute. */ void clear_can_read_revisions() { MutableStorage()->removeMember("canReadRevisions"); } /** * Get the value of the '<code>canReadRevisions</code>' attribute. */ bool get_can_read_revisions() const { const Json::Value& storage = Storage("canReadRevisions"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canReadRevisions</code>' attribute. * * Whether the current user can read the revisions resource of files in this * Team Drive. * * @param[in] value The new value. */ void set_can_read_revisions(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canReadRevisions")); } /** * Determine if the '<code>canRemoveChildren</code>' attribute was set. * * @return true if the '<code>canRemoveChildren</code>' attribute was set. */ bool has_can_remove_children() const { return Storage().isMember("canRemoveChildren"); } /** * Clears the '<code>canRemoveChildren</code>' attribute. */ void clear_can_remove_children() { MutableStorage()->removeMember("canRemoveChildren"); } /** * Get the value of the '<code>canRemoveChildren</code>' attribute. */ bool get_can_remove_children() const { const Json::Value& storage = Storage("canRemoveChildren"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canRemoveChildren</code>' attribute. * * Whether the current user can remove children from folders in this Team * Drive. * * @param[in] value The new value. */ void set_can_remove_children(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canRemoveChildren")); } /** * Determine if the '<code>canRename</code>' attribute was set. * * @return true if the '<code>canRename</code>' attribute was set. */ bool has_can_rename() const { return Storage().isMember("canRename"); } /** * Clears the '<code>canRename</code>' attribute. */ void clear_can_rename() { MutableStorage()->removeMember("canRename"); } /** * Get the value of the '<code>canRename</code>' attribute. */ bool get_can_rename() const { const Json::Value& storage = Storage("canRename"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canRename</code>' attribute. * * Whether the current user can rename files or folders in this Team Drive. * * @param[in] value The new value. */ void set_can_rename(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canRename")); } /** * Determine if the '<code>canRenameTeamDrive</code>' attribute was set. * * @return true if the '<code>canRenameTeamDrive</code>' attribute was set. */ bool has_can_rename_team_drive() const { return Storage().isMember("canRenameTeamDrive"); } /** * Clears the '<code>canRenameTeamDrive</code>' attribute. */ void clear_can_rename_team_drive() { MutableStorage()->removeMember("canRenameTeamDrive"); } /** * Get the value of the '<code>canRenameTeamDrive</code>' attribute. */ bool get_can_rename_team_drive() const { const Json::Value& storage = Storage("canRenameTeamDrive"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canRenameTeamDrive</code>' attribute. * * Whether the current user can rename this Team Drive. * * @param[in] value The new value. */ void set_can_rename_team_drive(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canRenameTeamDrive")); } /** * Determine if the '<code>canShare</code>' attribute was set. * * @return true if the '<code>canShare</code>' attribute was set. */ bool has_can_share() const { return Storage().isMember("canShare"); } /** * Clears the '<code>canShare</code>' attribute. */ void clear_can_share() { MutableStorage()->removeMember("canShare"); } /** * Get the value of the '<code>canShare</code>' attribute. */ bool get_can_share() const { const Json::Value& storage = Storage("canShare"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canShare</code>' attribute. * * Whether the current user can share files or folders in this Team Drive. * * @param[in] value The new value. */ void set_can_share(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canShare")); } private: void operator=(const TeamDriveCapabilities&); }; // TeamDriveCapabilities /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static TeamDrive* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit TeamDrive(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit TeamDrive(Json::Value* storage); /** * Standard destructor. */ virtual ~TeamDrive(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::TeamDrive</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::TeamDrive"); } /** * Determine if the '<code>backgroundImageFile</code>' attribute was set. * * @return true if the '<code>backgroundImageFile</code>' attribute was set. */ bool has_background_image_file() const { return Storage().isMember("backgroundImageFile"); } /** * Clears the '<code>backgroundImageFile</code>' attribute. */ void clear_background_image_file() { MutableStorage()->removeMember("backgroundImageFile"); } /** * Get a reference to the value of the '<code>backgroundImageFile</code>' * attribute. */ const TeamDriveBackgroundImageFile get_background_image_file() const { const Json::Value& storage = Storage("backgroundImageFile"); return client::JsonValueToCppValueHelper<TeamDriveBackgroundImageFile >(storage); } /** * Gets a reference to a mutable value of the * '<code>backgroundImageFile</code>' property. * * An image file and cropping parameters from which a background image for * this Team Drive is set. This is a write only field; it can only be set on * drive.teamdrives.update requests that don't set themeId. When specified, * all fields of the backgroundImageFile must be set. * * @return The result can be modified to change the attribute value. */ TeamDriveBackgroundImageFile mutable_backgroundImageFile() { Json::Value* storage = MutableStorage("backgroundImageFile"); return client::JsonValueToMutableCppValueHelper<TeamDriveBackgroundImageFile >(storage); } /** * Determine if the '<code>backgroundImageLink</code>' attribute was set. * * @return true if the '<code>backgroundImageLink</code>' attribute was set. */ bool has_background_image_link() const { return Storage().isMember("backgroundImageLink"); } /** * Clears the '<code>backgroundImageLink</code>' attribute. */ void clear_background_image_link() { MutableStorage()->removeMember("backgroundImageLink"); } /** * Get the value of the '<code>backgroundImageLink</code>' attribute. */ const StringPiece get_background_image_link() const { const Json::Value& v = Storage("backgroundImageLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>backgroundImageLink</code>' attribute. * * A short-lived link to this Team Drive's background image. * * @param[in] value The new value. */ void set_background_image_link(const StringPiece& value) { *MutableStorage("backgroundImageLink") = value.data(); } /** * Determine if the '<code>capabilities</code>' attribute was set. * * @return true if the '<code>capabilities</code>' attribute was set. */ bool has_capabilities() const { return Storage().isMember("capabilities"); } /** * Clears the '<code>capabilities</code>' attribute. */ void clear_capabilities() { MutableStorage()->removeMember("capabilities"); } /** * Get a reference to the value of the '<code>capabilities</code>' attribute. */ const TeamDriveCapabilities get_capabilities() const { const Json::Value& storage = Storage("capabilities"); return client::JsonValueToCppValueHelper<TeamDriveCapabilities >(storage); } /** * Gets a reference to a mutable value of the '<code>capabilities</code>' * property. * * Capabilities the current user has on this Team Drive. * * @return The result can be modified to change the attribute value. */ TeamDriveCapabilities mutable_capabilities() { Json::Value* storage = MutableStorage("capabilities"); return client::JsonValueToMutableCppValueHelper<TeamDriveCapabilities >(storage); } /** * Determine if the '<code>colorRgb</code>' attribute was set. * * @return true if the '<code>colorRgb</code>' attribute was set. */ bool has_color_rgb() const { return Storage().isMember("colorRgb"); } /** * Clears the '<code>colorRgb</code>' attribute. */ void clear_color_rgb() { MutableStorage()->removeMember("colorRgb"); } /** * Get the value of the '<code>colorRgb</code>' attribute. */ const StringPiece get_color_rgb() const { const Json::Value& v = Storage("colorRgb"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>colorRgb</code>' attribute. * * The color of this Team Drive as an RGB hex string. It can only be set on a * drive.teamdrives.update request that does not set themeId. * * @param[in] value The new value. */ void set_color_rgb(const StringPiece& value) { *MutableStorage("colorRgb") = value.data(); } /** * Determine if the '<code>id</code>' attribute was set. * * @return true if the '<code>id</code>' attribute was set. */ bool has_id() const { return Storage().isMember("id"); } /** * Clears the '<code>id</code>' attribute. */ void clear_id() { MutableStorage()->removeMember("id"); } /** * Get the value of the '<code>id</code>' attribute. */ const StringPiece get_id() const { const Json::Value& v = Storage("id"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>id</code>' attribute. * * The ID of this Team Drive which is also the ID of the top level folder for * this Team Drive. * * @param[in] value The new value. */ void set_id(const StringPiece& value) { *MutableStorage("id") = value.data(); } /** * Determine if the '<code>kind</code>' attribute was set. * * @return true if the '<code>kind</code>' attribute was set. */ bool has_kind() const { return Storage().isMember("kind"); } /** * Clears the '<code>kind</code>' attribute. */ void clear_kind() { MutableStorage()->removeMember("kind"); } /** * Get the value of the '<code>kind</code>' attribute. */ const StringPiece get_kind() const { const Json::Value& v = Storage("kind"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kind</code>' attribute. * * This is always drive#teamDrive. * * @param[in] value The new value. */ void set_kind(const StringPiece& value) { *MutableStorage("kind") = value.data(); } /** * Determine if the '<code>name</code>' attribute was set. * * @return true if the '<code>name</code>' attribute was set. */ bool has_name() const { return Storage().isMember("name"); } /** * Clears the '<code>name</code>' attribute. */ void clear_name() { MutableStorage()->removeMember("name"); } /** * Get the value of the '<code>name</code>' attribute. */ const StringPiece get_name() const { const Json::Value& v = Storage("name"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>name</code>' attribute. * * The name of this Team Drive. * * @param[in] value The new value. */ void set_name(const StringPiece& value) { *MutableStorage("name") = value.data(); } /** * Determine if the '<code>themeId</code>' attribute was set. * * @return true if the '<code>themeId</code>' attribute was set. */ bool has_theme_id() const { return Storage().isMember("themeId"); } /** * Clears the '<code>themeId</code>' attribute. */ void clear_theme_id() { MutableStorage()->removeMember("themeId"); } /** * Get the value of the '<code>themeId</code>' attribute. */ const StringPiece get_theme_id() const { const Json::Value& v = Storage("themeId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>themeId</code>' attribute. * * The ID of the theme from which the background image and color will be set. * The set of possible teamDriveThemes can be retrieved from a drive.about.get * response. When not specified on a drive.teamdrives.insert request, a random * theme is chosen from which the background image and color are set. This is * a write-only field; it can only be set on requests that don't set colorRgb * or backgroundImageFile. * * @param[in] value The new value. */ void set_theme_id(const StringPiece& value) { *MutableStorage("themeId") = value.data(); } private: void operator=(const TeamDrive&); }; // TeamDrive } // namespace google_drive_api #endif // GOOGLE_DRIVE_API_TEAM_DRIVE_H_ <file_sep>/src/googleapis/client/auth/oauth2_service_authorization.h /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #ifndef GOOGLEAPIS_AUTH_OAUTH2_SERVICE_AUTHORIZATION_H_ #define GOOGLEAPIS_AUTH_OAUTH2_SERVICE_AUTHORIZATION_H_ #include <string> using std::string; #include "googleapis/client/auth/oauth2_authorization.h" #include "googleapis/client/util/status.h" #include "googleapis/base/macros.h" namespace googleapis { namespace client { /* * An OAuth 2.0 flow for service accounts to get access tokens. * * To create an instance of this flow you must explicitly instantiate one * then call the InitFromJson or InitFromClientSecretsPath with a project * that was created as a Service Account. * * The generic factory method * OAuth2AuthorizationFlow::MakeFlowFromClientSecretsPath * will not create one of these flows because the secrets file format returned * by the OAuth2.0 server is not explicit about being a service account. */ class OAuth2ServiceAccountFlow : public OAuth2AuthorizationFlow { public: explicit OAuth2ServiceAccountFlow(HttpTransport* transport); virtual ~OAuth2ServiceAccountFlow(); /* * Sets the issuer (iss) attribute for the service account. * * This will be pulled from the client secrets file during Init() if present. */ void set_client_email(const string& email) { client_email_ = email; } /* * Returns the service account (typically from the client secrets file). */ const string& client_email() const { return client_email_; } /* * Sets the path of a Pkcs12 private key (typically from the API console). * * The actual key will be loaded later as needed but kept on disk. * * @return This method will fail if the path is not user-read only * as a precaution. * * @see SetPrivateKeyFromPkcs12Path */ googleapis::util::Status SetPrivateKeyPkcs12Path(const string& path); /* * Explicitly sets the private key. */ void set_private_key(const string& key); /* * Refreshes the credential as an OAuth 2.0 Service Account. */ virtual googleapis::util::Status PerformRefreshToken( const OAuth2RequestOptions& options, OAuth2Credential* credential); protected: virtual googleapis::util::Status InitFromJsonData(const SimpleJsonData* data); string MakeJwtClaims(const OAuth2RequestOptions& options) const; googleapis::util::Status ConstructSignedJwt( const string& plain_claims, string* result) const; private: string client_email_; string private_key_; // typically disjoint with p12_path_ string p12_path_; // typically disjoint with private_key_ googleapis::util::Status MakeJwt(const string& claims, string* jwt) const; DISALLOW_COPY_AND_ASSIGN(OAuth2ServiceAccountFlow); }; } // namespace client } // namespace googleapis #endif // GOOGLEAPIS_AUTH_OAUTH2_SERVICE_AUTHORIZATION_H_ <file_sep>/service_apis/youtube/google/youtube_api/live_broadcast.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Description: // Supports core YouTube features, such as uploading videos, creating and managing playlists, searching for content, and much more. // Classes: // LiveBroadcast // Documentation: // https://developers.google.com/youtube/v3 #include "google/youtube_api/live_broadcast.h" #include <string> #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/live_broadcast_content_details.h" #include "google/youtube_api/live_broadcast_snippet.h" #include "google/youtube_api/live_broadcast_statistics.h" #include "google/youtube_api/live_broadcast_status.h" #include "google/youtube_api/live_broadcast_topic_details.h" #include <string> #include "googleapis/strings/strcat.h" namespace google_youtube_api { using namespace googleapis; // Object factory method (static). LiveBroadcast* LiveBroadcast::New() { return new client::JsonCppCapsule<LiveBroadcast>; } // Standard immutable constructor. LiveBroadcast::LiveBroadcast(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. LiveBroadcast::LiveBroadcast(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. LiveBroadcast::~LiveBroadcast() { } // Properties. const LiveBroadcastContentDetails LiveBroadcast::get_content_details() const { const Json::Value& storage = Storage("contentDetails"); return client::JsonValueToCppValueHelper<LiveBroadcastContentDetails >(storage); } LiveBroadcastContentDetails LiveBroadcast::mutable_contentDetails() { Json::Value* storage = MutableStorage("contentDetails"); return client::JsonValueToMutableCppValueHelper<LiveBroadcastContentDetails >(storage); } const LiveBroadcastSnippet LiveBroadcast::get_snippet() const { const Json::Value& storage = Storage("snippet"); return client::JsonValueToCppValueHelper<LiveBroadcastSnippet >(storage); } LiveBroadcastSnippet LiveBroadcast::mutable_snippet() { Json::Value* storage = MutableStorage("snippet"); return client::JsonValueToMutableCppValueHelper<LiveBroadcastSnippet >(storage); } const LiveBroadcastStatistics LiveBroadcast::get_statistics() const { const Json::Value& storage = Storage("statistics"); return client::JsonValueToCppValueHelper<LiveBroadcastStatistics >(storage); } LiveBroadcastStatistics LiveBroadcast::mutable_statistics() { Json::Value* storage = MutableStorage("statistics"); return client::JsonValueToMutableCppValueHelper<LiveBroadcastStatistics >(storage); } const LiveBroadcastStatus LiveBroadcast::get_status() const { const Json::Value& storage = Storage("status"); return client::JsonValueToCppValueHelper<LiveBroadcastStatus >(storage); } LiveBroadcastStatus LiveBroadcast::mutable_status() { Json::Value* storage = MutableStorage("status"); return client::JsonValueToMutableCppValueHelper<LiveBroadcastStatus >(storage); } const LiveBroadcastTopicDetails LiveBroadcast::get_topic_details() const { const Json::Value& storage = Storage("topicDetails"); return client::JsonValueToCppValueHelper<LiveBroadcastTopicDetails >(storage); } LiveBroadcastTopicDetails LiveBroadcast::mutable_topicDetails() { Json::Value* storage = MutableStorage("topicDetails"); return client::JsonValueToMutableCppValueHelper<LiveBroadcastTopicDetails >(storage); } } // namespace google_youtube_api <file_sep>/service_apis/youtube/google/youtube_api/CMakeLists.txt # This is a CMake file for YouTube Data API v3 # using the Google APIs Client Library for C++. # # See http://google.github.io/google-api-cpp-client/latest/start/get_started # for more information about what to do with this file. project (google_youtube_api) # These sources assume that the CMakeLists.txt in ../.. added itself to # the include directories so that include paths are specified explicitly # with the directory #include "google/youtube_api/..." add_library(google_youtube_api STATIC access_policy.cc activity.cc activity_content_details.cc activity_content_details_bulletin.cc activity_content_details_channel_item.cc activity_content_details_comment.cc activity_content_details_favorite.cc activity_content_details_like.cc activity_content_details_playlist_item.cc activity_content_details_promoted_item.cc activity_content_details_recommendation.cc activity_content_details_social.cc activity_content_details_subscription.cc activity_content_details_upload.cc activity_list_response.cc activity_snippet.cc caption.cc caption_list_response.cc caption_snippet.cc cdn_settings.cc channel.cc channel_audit_details.cc channel_banner_resource.cc channel_branding_settings.cc channel_content_details.cc channel_content_owner_details.cc channel_conversion_ping.cc channel_conversion_pings.cc channel_list_response.cc channel_localization.cc channel_profile_details.cc channel_section.cc channel_section_content_details.cc channel_section_list_response.cc channel_section_localization.cc channel_section_snippet.cc channel_section_targeting.cc channel_settings.cc channel_snippet.cc channel_statistics.cc channel_status.cc channel_topic_details.cc comment.cc comment_list_response.cc comment_snippet.cc comment_thread.cc comment_thread_list_response.cc comment_thread_replies.cc comment_thread_snippet.cc content_rating.cc fan_funding_event.cc fan_funding_event_list_response.cc fan_funding_event_snippet.cc geo_point.cc guide_category.cc guide_category_list_response.cc guide_category_snippet.cc i18n_language.cc i18n_language_list_response.cc i18n_language_snippet.cc i18n_region.cc i18n_region_list_response.cc i18n_region_snippet.cc image_settings.cc ingestion_info.cc invideo_branding.cc invideo_position.cc invideo_promotion.cc invideo_timing.cc language_tag.cc live_broadcast.cc live_broadcast_content_details.cc live_broadcast_list_response.cc live_broadcast_snippet.cc live_broadcast_statistics.cc live_broadcast_status.cc live_broadcast_topic.cc live_broadcast_topic_details.cc live_broadcast_topic_snippet.cc live_chat_ban.cc live_chat_ban_snippet.cc live_chat_fan_funding_event_details.cc live_chat_message.cc live_chat_message_author_details.cc live_chat_message_deleted_details.cc live_chat_message_list_response.cc live_chat_message_retracted_details.cc live_chat_message_snippet.cc live_chat_moderator.cc live_chat_moderator_list_response.cc live_chat_moderator_snippet.cc live_chat_poll_closed_details.cc live_chat_poll_edited_details.cc live_chat_poll_item.cc live_chat_poll_opened_details.cc live_chat_poll_voted_details.cc live_chat_super_chat_details.cc live_chat_text_message_details.cc live_chat_user_banned_message_details.cc live_stream.cc live_stream_configuration_issue.cc live_stream_content_details.cc live_stream_health_status.cc live_stream_list_response.cc live_stream_snippet.cc live_stream_status.cc localized_property.cc localized_string.cc monitor_stream_info.cc page_info.cc playlist.cc playlist_content_details.cc playlist_item.cc playlist_item_content_details.cc playlist_item_list_response.cc playlist_item_snippet.cc playlist_item_status.cc playlist_list_response.cc playlist_localization.cc playlist_player.cc playlist_snippet.cc playlist_status.cc promoted_item.cc promoted_item_id.cc property_value.cc resource_id.cc search_list_response.cc search_result.cc search_result_snippet.cc sponsor.cc sponsor_list_response.cc sponsor_snippet.cc subscription.cc subscription_content_details.cc subscription_list_response.cc subscription_snippet.cc subscription_subscriber_snippet.cc super_chat_event.cc super_chat_event_list_response.cc super_chat_event_snippet.cc thumbnail.cc thumbnail_details.cc thumbnail_set_response.cc token_pagination.cc video.cc video_abuse_report.cc video_abuse_report_reason.cc video_abuse_report_reason_list_response.cc video_abuse_report_reason_snippet.cc video_abuse_report_secondary_reason.cc video_age_gating.cc video_category.cc video_category_list_response.cc video_category_snippet.cc video_content_details.cc video_content_details_region_restriction.cc video_file_details.cc video_file_details_audio_stream.cc video_file_details_video_stream.cc video_get_rating_response.cc video_list_response.cc video_live_streaming_details.cc video_localization.cc video_monetization_details.cc video_player.cc video_processing_details.cc video_processing_details_processing_progress.cc video_project_details.cc video_rating.cc video_recording_details.cc video_snippet.cc video_statistics.cc video_status.cc video_suggestions.cc video_suggestions_tag_suggestion.cc video_topic_details.cc watch_settings.cc you_tube_service.cc) target_link_libraries(google_youtube_api googleapis_http) target_link_libraries(google_youtube_api googleapis_internal) target_link_libraries(google_youtube_api googleapis_jsoncpp) target_link_libraries(google_youtube_api googleapis_utils) <file_sep>/service_apis/youtube/google/youtube_api/comment_thread_snippet.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_COMMENT_THREAD_SNIPPET_H_ #define GOOGLE_YOUTUBE_API_COMMENT_THREAD_SNIPPET_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/comment.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Basic details about a comment thread. * * @ingroup DataObject */ class CommentThreadSnippet : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static CommentThreadSnippet* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit CommentThreadSnippet(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit CommentThreadSnippet(Json::Value* storage); /** * Standard destructor. */ virtual ~CommentThreadSnippet(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::CommentThreadSnippet</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::CommentThreadSnippet"); } /** * Determine if the '<code>canReply</code>' attribute was set. * * @return true if the '<code>canReply</code>' attribute was set. */ bool has_can_reply() const { return Storage().isMember("canReply"); } /** * Clears the '<code>canReply</code>' attribute. */ void clear_can_reply() { MutableStorage()->removeMember("canReply"); } /** * Get the value of the '<code>canReply</code>' attribute. */ bool get_can_reply() const { const Json::Value& storage = Storage("canReply"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canReply</code>' attribute. * * Whether the current viewer of the thread can reply to it. This is viewer * specific - other viewers may see a different value for this field. * * @param[in] value The new value. */ void set_can_reply(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canReply")); } /** * Determine if the '<code>channelId</code>' attribute was set. * * @return true if the '<code>channelId</code>' attribute was set. */ bool has_channel_id() const { return Storage().isMember("channelId"); } /** * Clears the '<code>channelId</code>' attribute. */ void clear_channel_id() { MutableStorage()->removeMember("channelId"); } /** * Get the value of the '<code>channelId</code>' attribute. */ const StringPiece get_channel_id() const { const Json::Value& v = Storage("channelId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>channelId</code>' attribute. * * The YouTube channel the comments in the thread refer to or the channel with * the video the comments refer to. If video_id isn't set the comments refer * to the channel itself. * * @param[in] value The new value. */ void set_channel_id(const StringPiece& value) { *MutableStorage("channelId") = value.data(); } /** * Determine if the '<code>isPublic</code>' attribute was set. * * @return true if the '<code>isPublic</code>' attribute was set. */ bool has_is_public() const { return Storage().isMember("isPublic"); } /** * Clears the '<code>isPublic</code>' attribute. */ void clear_is_public() { MutableStorage()->removeMember("isPublic"); } /** * Get the value of the '<code>isPublic</code>' attribute. */ bool get_is_public() const { const Json::Value& storage = Storage("isPublic"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>isPublic</code>' attribute. * * Whether the thread (and therefore all its comments) is visible to all * YouTube users. * * @param[in] value The new value. */ void set_is_public(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("isPublic")); } /** * Determine if the '<code>topLevelComment</code>' attribute was set. * * @return true if the '<code>topLevelComment</code>' attribute was set. */ bool has_top_level_comment() const { return Storage().isMember("topLevelComment"); } /** * Clears the '<code>topLevelComment</code>' attribute. */ void clear_top_level_comment() { MutableStorage()->removeMember("topLevelComment"); } /** * Get a reference to the value of the '<code>topLevelComment</code>' * attribute. */ const Comment get_top_level_comment() const; /** * Gets a reference to a mutable value of the '<code>topLevelComment</code>' * property. * * The top level comment of this thread. * * @return The result can be modified to change the attribute value. */ Comment mutable_topLevelComment(); /** * Determine if the '<code>totalReplyCount</code>' attribute was set. * * @return true if the '<code>totalReplyCount</code>' attribute was set. */ bool has_total_reply_count() const { return Storage().isMember("totalReplyCount"); } /** * Clears the '<code>totalReplyCount</code>' attribute. */ void clear_total_reply_count() { MutableStorage()->removeMember("totalReplyCount"); } /** * Get the value of the '<code>totalReplyCount</code>' attribute. */ uint32 get_total_reply_count() const { const Json::Value& storage = Storage("totalReplyCount"); return client::JsonValueToCppValueHelper<uint32 >(storage); } /** * Change the '<code>totalReplyCount</code>' attribute. * * The total number of replies (not including the top level comment). * * @param[in] value The new value. */ void set_total_reply_count(uint32 value) { client::SetJsonValueFromCppValueHelper<uint32 >( value, MutableStorage("totalReplyCount")); } /** * Determine if the '<code>videoId</code>' attribute was set. * * @return true if the '<code>videoId</code>' attribute was set. */ bool has_video_id() const { return Storage().isMember("videoId"); } /** * Clears the '<code>videoId</code>' attribute. */ void clear_video_id() { MutableStorage()->removeMember("videoId"); } /** * Get the value of the '<code>videoId</code>' attribute. */ const StringPiece get_video_id() const { const Json::Value& v = Storage("videoId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>videoId</code>' attribute. * * The ID of the video the comments refer to, if any. No video_id implies a * channel discussion comment. * * @param[in] value The new value. */ void set_video_id(const StringPiece& value) { *MutableStorage("videoId") = value.data(); } private: void operator=(const CommentThreadSnippet&); }; // CommentThreadSnippet } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_COMMENT_THREAD_SNIPPET_H_ <file_sep>/service_apis/youtube/google/youtube_api/you_tube_service.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // //------------------------------------------------------------------------------ // This code was generated by google-apis-code-generator 1.5.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. //------------------------------------------------------------------------------ #ifndef GOOGLE_YOUTUBE_API_YOU_TUBE_SERVICE_H_ #define GOOGLE_YOUTUBE_API_YOU_TUBE_SERVICE_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/service/client_service.h" #include "googleapis/client/service/media_uploader.h" #include "googleapis/client/service/service_request_pager.h" #include "googleapis/client/util/date_time.h" #include "googleapis/client/util/status.h" #include "googleapis/client/util/uri_template.h" #include "google/youtube_api/activity.h" #include "google/youtube_api/activity_list_response.h" #include "google/youtube_api/caption.h" #include "google/youtube_api/caption_list_response.h" #include "google/youtube_api/channel.h" #include "google/youtube_api/channel_banner_resource.h" #include "google/youtube_api/channel_list_response.h" #include "google/youtube_api/channel_section.h" #include "google/youtube_api/channel_section_list_response.h" #include "google/youtube_api/comment.h" #include "google/youtube_api/comment_list_response.h" #include "google/youtube_api/comment_thread.h" #include "google/youtube_api/comment_thread_list_response.h" #include "google/youtube_api/fan_funding_event_list_response.h" #include "google/youtube_api/guide_category_list_response.h" #include "google/youtube_api/i18n_language_list_response.h" #include "google/youtube_api/i18n_region_list_response.h" #include "google/youtube_api/invideo_branding.h" #include "google/youtube_api/live_broadcast.h" #include "google/youtube_api/live_broadcast_list_response.h" #include "google/youtube_api/live_chat_ban.h" #include "google/youtube_api/live_chat_message.h" #include "google/youtube_api/live_chat_message_list_response.h" #include "google/youtube_api/live_chat_moderator.h" #include "google/youtube_api/live_chat_moderator_list_response.h" #include "google/youtube_api/live_stream.h" #include "google/youtube_api/live_stream_list_response.h" #include "google/youtube_api/playlist.h" #include "google/youtube_api/playlist_item.h" #include "google/youtube_api/playlist_item_list_response.h" #include "google/youtube_api/playlist_list_response.h" #include "google/youtube_api/search_list_response.h" #include "google/youtube_api/sponsor_list_response.h" #include "google/youtube_api/subscription.h" #include "google/youtube_api/subscription_list_response.h" #include "google/youtube_api/super_chat_event_list_response.h" #include "google/youtube_api/thumbnail_set_response.h" #include "google/youtube_api/video.h" #include "google/youtube_api/video_abuse_report.h" #include "google/youtube_api/video_abuse_report_reason_list_response.h" #include "google/youtube_api/video_category_list_response.h" #include "google/youtube_api/video_get_rating_response.h" #include "google/youtube_api/video_list_response.h" namespace google_youtube_api { using namespace googleapis; /** * \mainpage * YouTube Data API Version v3 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/youtube/v3'>YouTube Data API</a> * <tr><th>API Version<td>v3 * <tr><th>API Rev<td>20170130 * <tr><th>API Docs * <td><a href='https://developers.google.com/youtube/v3'> * https://developers.google.com/youtube/v3</a> * <tr><th>Discovery Name<td>youtube * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using YouTube Data API can be found at * <a href='https://developers.google.com/youtube/v3'>https://developers.google.com/youtube/v3</a>. * * For more information about the Google APIs Client Library for C++, see * <a href='https://developers.google.com/api-client-library/cpp/start/get_started'> * https://developers.google.com/api-client-library/cpp/start/get_started</a> */ class YouTubeService; /** * Implements a common base method for all methods within the YouTubeService. * * This class defines all the attributes common across all methods. * It does not pertain to any specific service API so is not normally * explicitly instantiated. */ class YouTubeServiceBaseRequest : public client::ClientServiceRequest { public: /** * Standard constructor. * * @param[in] service The service instance to send to when executed. * In practice this will be supplied internally by the service * when it acts as a method factory. * * @param[in] credential If not NULL then the credential to authorize with. * In practice this is supplied by the user code that is creating * the method instance. * * @param[in] method The HTTP method to use for the underlying HTTP request. * In practice this is specified by the particular API endpoint and * supplied internally by the derived class for that endpoint. * * @param[in] uri_template The <a href='http://tools.ietf.org/html/rfc6570'> * RFC 6570 URI Template</a> specifying the url to invoke * The parameters in the template should be resolvable attributes. * In practice this parameter is supplied internally by the derived * class for the endpoint. */ YouTubeServiceBaseRequest( const client::ClientService* service, client::AuthorizationCredential* credential, client::HttpRequest::HttpMethod method, const StringPiece& uri_template); /** * Standard destructor. */ virtual ~YouTubeServiceBaseRequest(); /** * Clears the '<code>alt</code>' attribute so it is no longer set. */ void clear_alt() { _have_alt_ = false; client::ClearCppValueHelper(&alt_); } /** * Gets the optional '<code>alt</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_alt() const { return alt_; } /** * Gets a modifiable pointer to the optional <code>alt</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_alt() { _have_alt_ = true; return &alt_; } /** * Sets the '<code>alt</code>' attribute. * * @param[in] value Data format for the response. */ void set_alt(const string& value) { _have_alt_ = true; alt_ = value; } /** * Clears the '<code>fields</code>' attribute so it is no longer set. */ void clear_fields() { _have_fields_ = false; client::ClearCppValueHelper(&fields_); } /** * Gets the optional '<code>fields</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_fields() const { return fields_; } /** * Gets a modifiable pointer to the optional <code>fields</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_fields() { _have_fields_ = true; return &fields_; } /** * Sets the '<code>fields</code>' attribute. * * @param[in] value Selector specifying which fields to include in a partial * response. */ void set_fields(const string& value) { _have_fields_ = true; fields_ = value; } /** * Clears the '<code>key</code>' attribute so it is no longer set. */ void clear_key() { _have_key_ = false; client::ClearCppValueHelper(&key_); } /** * Gets the optional '<code>key</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_key() const { return key_; } /** * Gets a modifiable pointer to the optional <code>key</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_key() { _have_key_ = true; return &key_; } /** * Sets the '<code>key</code>' attribute. * * @param[in] value API key. Your API key identifies your project and provides * you with API access, quota, and reports. Required unless you provide an * OAuth 2.0 token. */ void set_key(const string& value) { _have_key_ = true; key_ = value; } /** * Clears the '<code>oauth_token</code>' attribute so it is no longer set. */ void clear_oauth_token() { _have_oauth_token_ = false; client::ClearCppValueHelper(&oauth_token_); } /** * Gets the optional '<code>oauth_token</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_oauth_token() const { return oauth_token_; } /** * Gets a modifiable pointer to the optional <code>oauth_token</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_oauthToken() { _have_oauth_token_ = true; return &oauth_token_; } /** * Sets the '<code>oauth_token</code>' attribute. * * @param[in] value OAuth 2.0 token for the current user. */ void set_oauth_token(const string& value) { _have_oauth_token_ = true; oauth_token_ = value; } /** * Clears the '<code>prettyPrint</code>' attribute so it is no longer set. */ void clear_pretty_print() { _have_pretty_print_ = false; client::ClearCppValueHelper(&pretty_print_); } /** * Gets the optional '<code>prettyPrint</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_pretty_print() const { return pretty_print_; } /** * Sets the '<code>prettyPrint</code>' attribute. * * @param[in] value Returns response with indentations and line breaks. */ void set_pretty_print(bool value) { _have_pretty_print_ = true; pretty_print_ = value; } /** * Clears the '<code>quotaUser</code>' attribute so it is no longer set. */ void clear_quota_user() { _have_quota_user_ = false; client::ClearCppValueHelper(&quota_user_); } /** * Gets the optional '<code>quotaUser</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_quota_user() const { return quota_user_; } /** * Gets a modifiable pointer to the optional <code>quotaUser</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_quotaUser() { _have_quota_user_ = true; return &quota_user_; } /** * Sets the '<code>quotaUser</code>' attribute. * * @param[in] value Available to use for quota purposes for server-side * applications. Can be any arbitrary string assigned to a user, but should * not exceed 40 characters. Overrides userIp if both are provided. */ void set_quota_user(const string& value) { _have_quota_user_ = true; quota_user_ = value; } /** * Clears the '<code>userIp</code>' attribute so it is no longer set. */ void clear_user_ip() { _have_user_ip_ = false; client::ClearCppValueHelper(&user_ip_); } /** * Gets the optional '<code>userIp</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_user_ip() const { return user_ip_; } /** * Gets a modifiable pointer to the optional <code>userIp</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_userIp() { _have_user_ip_ = true; return &user_ip_; } /** * Sets the '<code>userIp</code>' attribute. * * @param[in] value IP address of the site where the request originates. Use * this if you want to enforce per-user limits. */ void set_user_ip(const string& value) { _have_user_ip_ = true; user_ip_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the * URI supplied to the constructor. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); protected: /** * Prepares the method's HTTP request to send body content as JSON. * * Only to be used for method constructors. */ void AddJsonContentToRequest(const client::JsonCppData *content); private: string alt_; string fields_; string key_; string oauth_token_; bool pretty_print_; string quota_user_; string user_ip_; bool _have_alt_ : 1; bool _have_fields_ : 1; bool _have_key_ : 1; bool _have_oauth_token_ : 1; bool _have_pretty_print_ : 1; bool _have_quota_user_ : 1; bool _have_user_ip_ : 1; DISALLOW_COPY_AND_ASSIGN(YouTubeServiceBaseRequest); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class ActivitiesResource_InsertMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * @param[in] _content_ The data object to insert. */ ActivitiesResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Activity& _content_); /** * Standard destructor. */ virtual ~ActivitiesResource_InsertMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Activity* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string _content_; DISALLOW_COPY_AND_ASSIGN(ActivitiesResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly */ class ActivitiesResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies a comma-separated list of one * or more activity resource properties that the API response will include. * * If the parameter identifies a property that contains child properties, the * child properties will be included in the response. For example, in an * activity resource, the snippet property contains other properties that * identify the type of activity, a display title for the activity, and so * forth. If you set part=snippet, the API response will also contain all of * those nested properties. */ ActivitiesResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~ActivitiesResource_ListMethod(); /** * Clears the '<code>channelId</code>' attribute so it is no longer set. */ void clear_channel_id() { _have_channel_id_ = false; client::ClearCppValueHelper(&channel_id_); } /** * Gets the optional '<code>channelId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_channel_id() const { return channel_id_; } /** * Gets a modifiable pointer to the optional <code>channelId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_channelId() { _have_channel_id_ = true; return &channel_id_; } /** * Sets the '<code>channelId</code>' attribute. * * @param[in] value The channelId parameter specifies a unique YouTube * channel ID. The API will then return a list of that channel's activities. */ void set_channel_id(const string& value) { _have_channel_id_ = true; channel_id_ = value; } /** * Clears the '<code>home</code>' attribute so it is no longer set. */ void clear_home() { _have_home_ = false; client::ClearCppValueHelper(&home_); } /** * Gets the optional '<code>home</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_home() const { return home_; } /** * Sets the '<code>home</code>' attribute. * * @param[in] value Set this parameter's value to true to retrieve the * activity feed that displays on the YouTube home page for the currently * authenticated user. */ void set_home(bool value) { _have_home_ = true; home_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * items that should be returned in the result set. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>mine</code>' attribute so it is no longer set. */ void clear_mine() { _have_mine_ = false; client::ClearCppValueHelper(&mine_); } /** * Gets the optional '<code>mine</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_mine() const { return mine_; } /** * Sets the '<code>mine</code>' attribute. * * @param[in] value Set this parameter's value to true to retrieve a feed of * the authenticated user's activities. */ void set_mine(bool value) { _have_mine_ = true; mine_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken and prevPageToken properties identify other pages that * could be retrieved. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Clears the '<code>publishedAfter</code>' attribute so it is no longer * set. */ void clear_published_after() { _have_published_after_ = false; client::ClearCppValueHelper(&published_after_); } /** * Gets the optional '<code>publishedAfter</code>' attribute. * * If the value is not set then the default value will be returned. */ client::DateTime get_published_after() const { return published_after_; } /** * Sets the '<code>publishedAfter</code>' attribute. * * @param[in] value The publishedAfter parameter specifies the earliest date * and time that an activity could have occurred for that activity to be * included in the API response. If the parameter value specifies a day, but * not a time, then any activities that occurred that day will be included * in the result set. The value is specified in ISO 8601 (YYYY-MM- * DDThh:mm:ss.sZ) format. */ void set_published_after(client::DateTime value) { _have_published_after_ = true; published_after_ = value; } /** * Clears the '<code>publishedBefore</code>' attribute so it is no longer * set. */ void clear_published_before() { _have_published_before_ = false; client::ClearCppValueHelper(&published_before_); } /** * Gets the optional '<code>publishedBefore</code>' attribute. * * If the value is not set then the default value will be returned. */ client::DateTime get_published_before() const { return published_before_; } /** * Sets the '<code>publishedBefore</code>' attribute. * * @param[in] value The publishedBefore parameter specifies the date and * time before which an activity must have occurred for that activity to be * included in the API response. If the parameter value specifies a day, but * not a time, then any activities that occurred that day will be excluded * from the result set. The value is specified in ISO 8601 (YYYY-MM- * DDThh:mm:ss.sZ) format. */ void set_published_before(client::DateTime value) { _have_published_before_ = true; published_before_ = value; } /** * Clears the '<code>regionCode</code>' attribute so it is no longer set. */ void clear_region_code() { _have_region_code_ = false; client::ClearCppValueHelper(&region_code_); } /** * Gets the optional '<code>regionCode</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_region_code() const { return region_code_; } /** * Gets a modifiable pointer to the optional <code>regionCode</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_regionCode() { _have_region_code_ = true; return &region_code_; } /** * Sets the '<code>regionCode</code>' attribute. * * @param[in] value The regionCode parameter instructs the API to return * results for the specified country. The parameter value is an ISO 3166-1 * alpha-2 country code. YouTube uses this value when the authorized user's * previous activity on YouTube does not provide enough information to * generate the activity feed. */ void set_region_code(const string& value) { _have_region_code_ = true; region_code_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( ActivityListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string channel_id_; bool home_; uint32 max_results_; bool mine_; string page_token_; client::DateTime published_after_; client::DateTime published_before_; string region_code_; bool _have_channel_id_ : 1; bool _have_home_ : 1; bool _have_max_results_ : 1; bool _have_mine_ : 1; bool _have_page_token_ : 1; bool _have_published_after_ : 1; bool _have_published_before_ : 1; bool _have_region_code_ : 1; DISALLOW_COPY_AND_ASSIGN(ActivitiesResource_ListMethod); }; typedef client::ServiceRequestPager< ActivitiesResource_ListMethod, ActivityListResponse> ActivitiesResource_ListMethodPager; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class CaptionsResource_DeleteMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter identifies the caption track that is being * deleted. The value is a caption track ID as identified by the id property * in a caption resource. */ CaptionsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id); /** * Standard destructor. */ virtual ~CaptionsResource_DeleteMethod(); /** * Clears the '<code>onBehalfOf</code>' attribute so it is no longer set. */ void clear_on_behalf_of() { _have_on_behalf_of_ = false; client::ClearCppValueHelper(&on_behalf_of_); } /** * Gets the optional '<code>onBehalfOf</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of() const { return on_behalf_of_; } /** * Gets a modifiable pointer to the optional <code>onBehalfOf</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOf() { _have_on_behalf_of_ = true; return &on_behalf_of_; } /** * Sets the '<code>onBehalfOf</code>' attribute. * * @param[in] value ID of the Google+ Page for the channel that the request * is be on behalf of. */ void set_on_behalf_of(const string& value) { _have_on_behalf_of_ = true; on_behalf_of_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * actual CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string id_; string on_behalf_of_; string on_behalf_of_content_owner_; bool _have_on_behalf_of_ : 1; bool _have_on_behalf_of_content_owner_ : 1; DISALLOW_COPY_AND_ASSIGN(CaptionsResource_DeleteMethod); }; /** * Implements the download method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class CaptionsResource_DownloadMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter identifies the caption track that is being * retrieved. The value is a caption track ID as identified by the id property * in a caption resource. */ CaptionsResource_DownloadMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id); /** * Standard destructor. */ virtual ~CaptionsResource_DownloadMethod(); /** * Clears the '<code>onBehalfOf</code>' attribute so it is no longer set. */ void clear_on_behalf_of() { _have_on_behalf_of_ = false; client::ClearCppValueHelper(&on_behalf_of_); } /** * Gets the optional '<code>onBehalfOf</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of() const { return on_behalf_of_; } /** * Gets a modifiable pointer to the optional <code>onBehalfOf</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOf() { _have_on_behalf_of_ = true; return &on_behalf_of_; } /** * Sets the '<code>onBehalfOf</code>' attribute. * * @param[in] value ID of the Google+ Page for the channel that the request * is be on behalf of. */ void set_on_behalf_of(const string& value) { _have_on_behalf_of_ = true; on_behalf_of_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * actual CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>tfmt</code>' attribute so it is no longer set. */ void clear_tfmt() { _have_tfmt_ = false; client::ClearCppValueHelper(&tfmt_); } /** * Gets the optional '<code>tfmt</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_tfmt() const { return tfmt_; } /** * Gets a modifiable pointer to the optional <code>tfmt</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_tfmt() { _have_tfmt_ = true; return &tfmt_; } /** * Sets the '<code>tfmt</code>' attribute. * * @param[in] value The tfmt parameter specifies that the caption track * should be returned in a specific format. If the parameter is not included * in the request, the track is returned in its original format. */ void set_tfmt(const string& value) { _have_tfmt_ = true; tfmt_ = value; } /** * Clears the '<code>tlang</code>' attribute so it is no longer set. */ void clear_tlang() { _have_tlang_ = false; client::ClearCppValueHelper(&tlang_); } /** * Gets the optional '<code>tlang</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_tlang() const { return tlang_; } /** * Gets a modifiable pointer to the optional <code>tlang</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_tlang() { _have_tlang_ = true; return &tlang_; } /** * Sets the '<code>tlang</code>' attribute. * * @param[in] value The tlang parameter specifies that the API response * should return a translation of the specified caption track. The parameter * value is an ISO 639-1 two-letter language code that identifies the * desired caption language. The translation is generated by using machine * translation, such as Google Translate. */ void set_tlang(const string& value) { _have_tlang_ = true; tlang_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Determine if the request should use Media Download for the response. * * @return true for media download, false otherwise. */ bool get_use_media_download() const { return YouTubeServiceBaseRequest::get_use_media_download(); } /** * Sets whether Media Download should be used for the response data. * * @param[in] use true to use media download, false otherwise. */ void set_use_media_download(bool use) { YouTubeServiceBaseRequest::set_use_media_download(use); } private: string id_; string on_behalf_of_; string on_behalf_of_content_owner_; string tfmt_; string tlang_; bool _have_on_behalf_of_ : 1; bool _have_on_behalf_of_content_owner_ : 1; bool _have_tfmt_ : 1; bool _have_tlang_ : 1; DISALLOW_COPY_AND_ASSIGN(CaptionsResource_DownloadMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class CaptionsResource_InsertMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * * @deprecated in favor constructor that includes the media upload parameters. * * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies the caption resource parts * that the API response will include. Set the parameter value to snippet. * * @param[in] _content_ The data object to insert. */ CaptionsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies the caption resource parts * that the API response will include. Set the parameter value to snippet. * @param[in] _metadata_ The metadata object to insert. If this * is NULL then do not upload any metadata. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to insert. If * this is NULL then do not upload any media and ignore * _media_content_type_. */ CaptionsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Caption* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_); /** * Standard destructor. */ virtual ~CaptionsResource_InsertMethod(); /** * Clears the '<code>onBehalfOf</code>' attribute so it is no longer set. */ void clear_on_behalf_of() { _have_on_behalf_of_ = false; client::ClearCppValueHelper(&on_behalf_of_); } /** * Gets the optional '<code>onBehalfOf</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of() const { return on_behalf_of_; } /** * Gets a modifiable pointer to the optional <code>onBehalfOf</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOf() { _have_on_behalf_of_ = true; return &on_behalf_of_; } /** * Sets the '<code>onBehalfOf</code>' attribute. * * @param[in] value ID of the Google+ Page for the channel that the request * is be on behalf of. */ void set_on_behalf_of(const string& value) { _have_on_behalf_of_ = true; on_behalf_of_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * actual CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>sync</code>' attribute so it is no longer set. */ void clear_sync() { _have_sync_ = false; client::ClearCppValueHelper(&sync_); } /** * Gets the optional '<code>sync</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_sync() const { return sync_; } /** * Sets the '<code>sync</code>' attribute. * * @param[in] value The sync parameter indicates whether YouTube should * automatically synchronize the caption file with the audio track of the * video. If you set the value to true, YouTube will disregard any time * codes that are in the uploaded caption file and generate new time codes * for the captions. * * You should set the sync parameter to true if you are uploading a * transcript, which has no time codes, or if you suspect the time codes in * your file are incorrect and want YouTube to try to fix them. */ void set_sync(bool value) { _have_sync_ = true; sync_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Caption* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } /** * Returns MediaUploader for uploading the content. */ /** * Returns the specification for media upload using the simple protocol. */ static const client::MediaUploadSpec SIMPLE_MEDIA_UPLOAD; /** * Returns the specification for media upload using the resumable protocol. */ static const client::MediaUploadSpec RESUMABLE_MEDIA_UPLOAD; private: string part_; string on_behalf_of_; string on_behalf_of_content_owner_; bool sync_; bool _have_on_behalf_of_ : 1; bool _have_on_behalf_of_content_owner_ : 1; bool _have_sync_ : 1; DISALLOW_COPY_AND_ASSIGN(CaptionsResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class CaptionsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies a comma-separated list of one * or more caption resource parts that the API response will include. The part * names that you can include in the parameter value are id and snippet. * @param[in] video_id The videoId parameter specifies the YouTube video ID of * the video for which the API should return caption tracks. */ CaptionsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const StringPiece& video_id); /** * Standard destructor. */ virtual ~CaptionsResource_ListMethod(); /** * Clears the '<code>id</code>' attribute so it is no longer set. */ void clear_id() { _have_id_ = false; client::ClearCppValueHelper(&id_); } /** * Gets the optional '<code>id</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_id() const { return id_; } /** * Gets a modifiable pointer to the optional <code>id</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_id() { _have_id_ = true; return &id_; } /** * Sets the '<code>id</code>' attribute. * * @param[in] value The id parameter specifies a comma-separated list of IDs * that identify the caption resources that should be retrieved. Each ID * must identify a caption track associated with the specified video. */ void set_id(const string& value) { _have_id_ = true; id_ = value; } /** * Clears the '<code>onBehalfOf</code>' attribute so it is no longer set. */ void clear_on_behalf_of() { _have_on_behalf_of_ = false; client::ClearCppValueHelper(&on_behalf_of_); } /** * Gets the optional '<code>onBehalfOf</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of() const { return on_behalf_of_; } /** * Gets a modifiable pointer to the optional <code>onBehalfOf</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOf() { _have_on_behalf_of_ = true; return &on_behalf_of_; } /** * Sets the '<code>onBehalfOf</code>' attribute. * * @param[in] value ID of the Google+ Page for the channel that the request * is on behalf of. */ void set_on_behalf_of(const string& value) { _have_on_behalf_of_ = true; on_behalf_of_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * actual CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( CaptionListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string video_id_; string id_; string on_behalf_of_; string on_behalf_of_content_owner_; bool _have_id_ : 1; bool _have_on_behalf_of_ : 1; bool _have_on_behalf_of_content_owner_ : 1; DISALLOW_COPY_AND_ASSIGN(CaptionsResource_ListMethod); }; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class CaptionsResource_UpdateMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * * @deprecated in favor constructor that includes the media upload parameters. * * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. Set the property value * to snippet if you are updating the track's draft status. Otherwise, set the * property value to id. * * @param[in] _content_ The data object to update. */ CaptionsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. Set the property value * to snippet if you are updating the track's draft status. Otherwise, set the * property value to id. * @param[in] _metadata_ The metadata object to update. If this * is NULL then do not upload any metadata. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to update. If * this is NULL then do not upload any media and ignore * _media_content_type_. */ CaptionsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Caption* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_); /** * Standard destructor. */ virtual ~CaptionsResource_UpdateMethod(); /** * Clears the '<code>onBehalfOf</code>' attribute so it is no longer set. */ void clear_on_behalf_of() { _have_on_behalf_of_ = false; client::ClearCppValueHelper(&on_behalf_of_); } /** * Gets the optional '<code>onBehalfOf</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of() const { return on_behalf_of_; } /** * Gets a modifiable pointer to the optional <code>onBehalfOf</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOf() { _have_on_behalf_of_ = true; return &on_behalf_of_; } /** * Sets the '<code>onBehalfOf</code>' attribute. * * @param[in] value ID of the Google+ Page for the channel that the request * is be on behalf of. */ void set_on_behalf_of(const string& value) { _have_on_behalf_of_ = true; on_behalf_of_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * actual CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>sync</code>' attribute so it is no longer set. */ void clear_sync() { _have_sync_ = false; client::ClearCppValueHelper(&sync_); } /** * Gets the optional '<code>sync</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_sync() const { return sync_; } /** * Sets the '<code>sync</code>' attribute. * * @param[in] value Note: The API server only processes the parameter value * if the request contains an updated caption file. * * The sync parameter indicates whether YouTube should automatically * synchronize the caption file with the audio track of the video. If you * set the value to true, YouTube will automatically synchronize the caption * track with the audio track. */ void set_sync(bool value) { _have_sync_ = true; sync_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Caption* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } /** * Returns MediaUploader for uploading the content. */ /** * Returns the specification for media upload using the simple protocol. */ static const client::MediaUploadSpec SIMPLE_MEDIA_UPLOAD; /** * Returns the specification for media upload using the resumable protocol. */ static const client::MediaUploadSpec RESUMABLE_MEDIA_UPLOAD; private: string part_; string on_behalf_of_; string on_behalf_of_content_owner_; bool sync_; bool _have_on_behalf_of_ : 1; bool _have_on_behalf_of_content_owner_ : 1; bool _have_sync_ : 1; DISALLOW_COPY_AND_ASSIGN(CaptionsResource_UpdateMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.upload */ class ChannelBannersResource_InsertMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * * @deprecated in favor constructor that includes the media upload parameters. * * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] _content_ The data object to insert. */ ChannelBannersResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_); /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] _metadata_ The metadata object to insert. If this * is NULL then do not upload any metadata. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to insert. If * this is NULL then do not upload any media and ignore * _media_content_type_. */ ChannelBannersResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const ChannelBannerResource* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_); /** * Standard destructor. */ virtual ~ChannelBannersResource_InsertMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( ChannelBannerResource* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } /** * Returns MediaUploader for uploading the content. */ /** * Returns the specification for media upload using the simple protocol. */ static const client::MediaUploadSpec SIMPLE_MEDIA_UPLOAD; /** * Returns the specification for media upload using the resumable protocol. */ static const client::MediaUploadSpec RESUMABLE_MEDIA_UPLOAD; private: string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; DISALLOW_COPY_AND_ASSIGN(ChannelBannersResource_InsertMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class ChannelSectionsResource_DeleteMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter specifies the YouTube channelSection ID for * the resource that is being deleted. In a channelSection resource, the id * property specifies the YouTube channelSection ID. */ ChannelSectionsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id); /** * Standard destructor. */ virtual ~ChannelSectionsResource_DeleteMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string id_; string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; DISALLOW_COPY_AND_ASSIGN(ChannelSectionsResource_DeleteMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class ChannelSectionsResource_InsertMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * The part names that you can include in the parameter value are snippet and * contentDetails. * @param[in] _content_ The data object to insert. */ ChannelSectionsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const ChannelSection& _content_); /** * Standard destructor. */ virtual ~ChannelSectionsResource_InsertMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( ChannelSection* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(ChannelSectionsResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly * https://www.googleapis.com/auth/youtubepartner */ class ChannelSectionsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies a comma-separated list of one * or more channelSection resource properties that the API response will * include. The part names that you can include in the parameter value are id, * snippet, and contentDetails. * * If the parameter identifies a property that contains child properties, the * child properties will be included in the response. For example, in a * channelSection resource, the snippet property contains other properties, * such as a display title for the channelSection. If you set part=snippet, * the API response will also contain all of those nested properties. */ ChannelSectionsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~ChannelSectionsResource_ListMethod(); /** * Clears the '<code>channelId</code>' attribute so it is no longer set. */ void clear_channel_id() { _have_channel_id_ = false; client::ClearCppValueHelper(&channel_id_); } /** * Gets the optional '<code>channelId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_channel_id() const { return channel_id_; } /** * Gets a modifiable pointer to the optional <code>channelId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_channelId() { _have_channel_id_ = true; return &channel_id_; } /** * Sets the '<code>channelId</code>' attribute. * * @param[in] value The channelId parameter specifies a YouTube channel ID. * The API will only return that channel's channelSections. */ void set_channel_id(const string& value) { _have_channel_id_ = true; channel_id_ = value; } /** * Clears the '<code>hl</code>' attribute so it is no longer set. */ void clear_hl() { _have_hl_ = false; client::ClearCppValueHelper(&hl_); } /** * Gets the optional '<code>hl</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_hl() const { return hl_; } /** * Gets a modifiable pointer to the optional <code>hl</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_hl() { _have_hl_ = true; return &hl_; } /** * Sets the '<code>hl</code>' attribute. * * @param[in] value The hl parameter indicates that the snippet.localized * property values in the returned channelSection resources should be in the * specified language if localized values for that language are available. * For example, if the API request specifies hl=de, the snippet.localized * properties in the API response will contain German titles if German * titles are available. Channel owners can provide localized channel * section titles using either the channelSections.insert or * channelSections.update method. */ void set_hl(const string& value) { _have_hl_ = true; hl_ = value; } /** * Clears the '<code>id</code>' attribute so it is no longer set. */ void clear_id() { _have_id_ = false; client::ClearCppValueHelper(&id_); } /** * Gets the optional '<code>id</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_id() const { return id_; } /** * Gets a modifiable pointer to the optional <code>id</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_id() { _have_id_ = true; return &id_; } /** * Sets the '<code>id</code>' attribute. * * @param[in] value The id parameter specifies a comma-separated list of the * YouTube channelSection ID(s) for the resource(s) that are being * retrieved. In a channelSection resource, the id property specifies the * YouTube channelSection ID. */ void set_id(const string& value) { _have_id_ = true; id_ = value; } /** * Clears the '<code>mine</code>' attribute so it is no longer set. */ void clear_mine() { _have_mine_ = false; client::ClearCppValueHelper(&mine_); } /** * Gets the optional '<code>mine</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_mine() const { return mine_; } /** * Sets the '<code>mine</code>' attribute. * * @param[in] value Set this parameter's value to true to retrieve a feed of * the authenticated user's channelSections. */ void set_mine(bool value) { _have_mine_ = true; mine_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( ChannelSectionListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string channel_id_; string hl_; string id_; bool mine_; string on_behalf_of_content_owner_; bool _have_channel_id_ : 1; bool _have_hl_ : 1; bool _have_id_ : 1; bool _have_mine_ : 1; bool _have_on_behalf_of_content_owner_ : 1; DISALLOW_COPY_AND_ASSIGN(ChannelSectionsResource_ListMethod); }; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class ChannelSectionsResource_UpdateMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * The part names that you can include in the parameter value are snippet and * contentDetails. * @param[in] _content_ The data object to update. */ ChannelSectionsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const ChannelSection& _content_); /** * Standard destructor. */ virtual ~ChannelSectionsResource_UpdateMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( ChannelSection* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(ChannelSectionsResource_UpdateMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly * https://www.googleapis.com/auth/youtubepartner * https://www.googleapis.com/auth/youtubepartner-channel-audit */ class ChannelsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies a comma-separated list of one * or more channel resource properties that the API response will include. * * If the parameter identifies a property that contains child properties, the * child properties will be included in the response. For example, in a * channel resource, the contentDetails property contains other properties, * such as the uploads properties. As such, if you set part=contentDetails, * the API response will also contain all of those nested properties. */ ChannelsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~ChannelsResource_ListMethod(); /** * Clears the '<code>categoryId</code>' attribute so it is no longer set. */ void clear_category_id() { _have_category_id_ = false; client::ClearCppValueHelper(&category_id_); } /** * Gets the optional '<code>categoryId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_category_id() const { return category_id_; } /** * Gets a modifiable pointer to the optional <code>categoryId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_categoryId() { _have_category_id_ = true; return &category_id_; } /** * Sets the '<code>categoryId</code>' attribute. * * @param[in] value The categoryId parameter specifies a YouTube guide * category, thereby requesting YouTube channels associated with that * category. */ void set_category_id(const string& value) { _have_category_id_ = true; category_id_ = value; } /** * Clears the '<code>forUsername</code>' attribute so it is no longer set. */ void clear_for_username() { _have_for_username_ = false; client::ClearCppValueHelper(&for_username_); } /** * Gets the optional '<code>forUsername</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_for_username() const { return for_username_; } /** * Gets a modifiable pointer to the optional <code>forUsername</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_forUsername() { _have_for_username_ = true; return &for_username_; } /** * Sets the '<code>forUsername</code>' attribute. * * @param[in] value The forUsername parameter specifies a YouTube username, * thereby requesting the channel associated with that username. */ void set_for_username(const string& value) { _have_for_username_ = true; for_username_ = value; } /** * Clears the '<code>hl</code>' attribute so it is no longer set. */ void clear_hl() { _have_hl_ = false; client::ClearCppValueHelper(&hl_); } /** * Gets the optional '<code>hl</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_hl() const { return hl_; } /** * Gets a modifiable pointer to the optional <code>hl</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_hl() { _have_hl_ = true; return &hl_; } /** * Sets the '<code>hl</code>' attribute. * * @param[in] value The hl parameter should be used for filter out the * properties that are not in the given language. Used for the * brandingSettings part. */ void set_hl(const string& value) { _have_hl_ = true; hl_ = value; } /** * Clears the '<code>id</code>' attribute so it is no longer set. */ void clear_id() { _have_id_ = false; client::ClearCppValueHelper(&id_); } /** * Gets the optional '<code>id</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_id() const { return id_; } /** * Gets a modifiable pointer to the optional <code>id</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_id() { _have_id_ = true; return &id_; } /** * Sets the '<code>id</code>' attribute. * * @param[in] value The id parameter specifies a comma-separated list of the * YouTube channel ID(s) for the resource(s) that are being retrieved. In a * channel resource, the id property specifies the channel's YouTube channel * ID. */ void set_id(const string& value) { _have_id_ = true; id_ = value; } /** * Clears the '<code>managedByMe</code>' attribute so it is no longer set. */ void clear_managed_by_me() { _have_managed_by_me_ = false; client::ClearCppValueHelper(&managed_by_me_); } /** * Gets the optional '<code>managedByMe</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_managed_by_me() const { return managed_by_me_; } /** * Sets the '<code>managedByMe</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * Set this parameter's value to true to instruct the API to only return * channels managed by the content owner that the onBehalfOfContentOwner * parameter specifies. The user must be authenticated as a CMS account * linked to the specified content owner and onBehalfOfContentOwner must be * provided. */ void set_managed_by_me(bool value) { _have_managed_by_me_ = true; managed_by_me_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * items that should be returned in the result set. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>mine</code>' attribute so it is no longer set. */ void clear_mine() { _have_mine_ = false; client::ClearCppValueHelper(&mine_); } /** * Gets the optional '<code>mine</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_mine() const { return mine_; } /** * Sets the '<code>mine</code>' attribute. * * @param[in] value Set this parameter's value to true to instruct the API * to only return channels owned by the authenticated user. */ void set_mine(bool value) { _have_mine_ = true; mine_ = value; } /** * Clears the '<code>mySubscribers</code>' attribute so it is no longer set. */ void clear_my_subscribers() { _have_my_subscribers_ = false; client::ClearCppValueHelper(&my_subscribers_); } /** * Gets the optional '<code>mySubscribers</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_my_subscribers() const { return my_subscribers_; } /** * Sets the '<code>mySubscribers</code>' attribute. * * @param[in] value Use the subscriptions.list method and its mySubscribers * parameter to retrieve a list of subscribers to the authenticated user's * channel. */ void set_my_subscribers(bool value) { _have_my_subscribers_ = true; my_subscribers_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken and prevPageToken properties identify other pages that * could be retrieved. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( ChannelListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string category_id_; string for_username_; string hl_; string id_; bool managed_by_me_; uint32 max_results_; bool mine_; bool my_subscribers_; string on_behalf_of_content_owner_; string page_token_; bool _have_category_id_ : 1; bool _have_for_username_ : 1; bool _have_hl_ : 1; bool _have_id_ : 1; bool _have_managed_by_me_ : 1; bool _have_max_results_ : 1; bool _have_mine_ : 1; bool _have_my_subscribers_ : 1; bool _have_on_behalf_of_content_owner_ : 1; bool _have_page_token_ : 1; DISALLOW_COPY_AND_ASSIGN(ChannelsResource_ListMethod); }; typedef client::ServiceRequestPager< ChannelsResource_ListMethod, ChannelListResponse> ChannelsResource_ListMethodPager; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class ChannelsResource_UpdateMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * The API currently only allows the parameter value to be set to either * brandingSettings or invideoPromotion. (You cannot update both of those * parts with a single request.) * * Note that this method overrides the existing values for all of the mutable * properties that are contained in any parts that the parameter value * specifies. * @param[in] _content_ The data object to update. */ ChannelsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Channel& _content_); /** * Standard destructor. */ virtual ~ChannelsResource_UpdateMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value The onBehalfOfContentOwner parameter indicates that the * authenticated user is acting on behalf of the content owner specified in * the parameter value. This parameter is intended for YouTube content * partners that own and manage many different YouTube channels. It allows * content owners to authenticate once and get access to all their video and * channel data, without having to provide authentication credentials for * each individual channel. The actual CMS account that the user * authenticates with needs to be linked to the specified YouTube content * owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Channel* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(ChannelsResource_UpdateMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube.force-ssl */ class CommentThreadsResource_InsertMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter identifies the properties that the API * response will include. Set the parameter value to snippet. The snippet part * has a quota cost of 2 units. * @param[in] _content_ The data object to insert. */ CommentThreadsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const CommentThread& _content_); /** * Standard destructor. */ virtual ~CommentThreadsResource_InsertMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( CommentThread* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string _content_; DISALLOW_COPY_AND_ASSIGN(CommentThreadsResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube.force-ssl */ class CommentThreadsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies a comma-separated list of one * or more commentThread resource properties that the API response will * include. */ CommentThreadsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~CommentThreadsResource_ListMethod(); /** * Clears the '<code>allThreadsRelatedToChannelId</code>' attribute so it is * no longer set. */ void clear_all_threads_related_to_channel_id() { _have_all_threads_related_to_channel_id_ = false; client::ClearCppValueHelper(&all_threads_related_to_channel_id_); } /** * Gets the optional '<code>allThreadsRelatedToChannelId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_all_threads_related_to_channel_id() const { return all_threads_related_to_channel_id_; } /** * Gets a modifiable pointer to the optional * <code>allThreadsRelatedToChannelId</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_allThreadsRelatedToChannelId() { _have_all_threads_related_to_channel_id_ = true; return &all_threads_related_to_channel_id_; } /** * Sets the '<code>allThreadsRelatedToChannelId</code>' attribute. * * @param[in] value The allThreadsRelatedToChannelId parameter instructs the * API to return all comment threads associated with the specified channel. * The response can include comments about the channel or about the * channel's videos. */ void set_all_threads_related_to_channel_id(const string& value) { _have_all_threads_related_to_channel_id_ = true; all_threads_related_to_channel_id_ = value; } /** * Clears the '<code>channelId</code>' attribute so it is no longer set. */ void clear_channel_id() { _have_channel_id_ = false; client::ClearCppValueHelper(&channel_id_); } /** * Gets the optional '<code>channelId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_channel_id() const { return channel_id_; } /** * Gets a modifiable pointer to the optional <code>channelId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_channelId() { _have_channel_id_ = true; return &channel_id_; } /** * Sets the '<code>channelId</code>' attribute. * * @param[in] value The channelId parameter instructs the API to return * comment threads containing comments about the specified channel. (The * response will not include comments left on videos that the channel * uploaded.). */ void set_channel_id(const string& value) { _have_channel_id_ = true; channel_id_ = value; } /** * Clears the '<code>id</code>' attribute so it is no longer set. */ void clear_id() { _have_id_ = false; client::ClearCppValueHelper(&id_); } /** * Gets the optional '<code>id</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_id() const { return id_; } /** * Gets a modifiable pointer to the optional <code>id</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_id() { _have_id_ = true; return &id_; } /** * Sets the '<code>id</code>' attribute. * * @param[in] value The id parameter specifies a comma-separated list of * comment thread IDs for the resources that should be retrieved. */ void set_id(const string& value) { _have_id_ = true; id_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * items that should be returned in the result set. * * Note: This parameter is not supported for use in conjunction with the id * parameter. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>moderationStatus</code>' attribute so it is no longer * set. */ void clear_moderation_status() { _have_moderation_status_ = false; client::ClearCppValueHelper(&moderation_status_); } /** * Gets the optional '<code>moderationStatus</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_moderation_status() const { return moderation_status_; } /** * Gets a modifiable pointer to the optional <code>moderationStatus</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_moderationStatus() { _have_moderation_status_ = true; return &moderation_status_; } /** * Sets the '<code>moderationStatus</code>' attribute. * * @param[in] value Set this parameter to limit the returned comment threads * to a particular moderation state. * * Note: This parameter is not supported for use in conjunction with the id * parameter. */ void set_moderation_status(const string& value) { _have_moderation_status_ = true; moderation_status_ = value; } /** * Clears the '<code>order</code>' attribute so it is no longer set. */ void clear_order() { _have_order_ = false; client::ClearCppValueHelper(&order_); } /** * Gets the optional '<code>order</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_order() const { return order_; } /** * Gets a modifiable pointer to the optional <code>order</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_order() { _have_order_ = true; return &order_; } /** * Sets the '<code>order</code>' attribute. * * @param[in] value The order parameter specifies the order in which the API * response should list comment threads. Valid values are: * <dl> * <dt>time * <dd>Comment threads are ordered by time. This is the default behavior. * <dt>relevance * <dd>Comment threads are ordered by relevance.Note: This parameter is not * supported for use in conjunction with the id parameter. * </dl> * */ void set_order(const string& value) { _have_order_ = true; order_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken property identifies the next page of the result that can be * retrieved. * * Note: This parameter is not supported for use in conjunction with the id * parameter. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Clears the '<code>searchTerms</code>' attribute so it is no longer set. */ void clear_search_terms() { _have_search_terms_ = false; client::ClearCppValueHelper(&search_terms_); } /** * Gets the optional '<code>searchTerms</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_search_terms() const { return search_terms_; } /** * Gets a modifiable pointer to the optional <code>searchTerms</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_searchTerms() { _have_search_terms_ = true; return &search_terms_; } /** * Sets the '<code>searchTerms</code>' attribute. * * @param[in] value The searchTerms parameter instructs the API to limit the * API response to only contain comments that contain the specified search * terms. * * Note: This parameter is not supported for use in conjunction with the id * parameter. */ void set_search_terms(const string& value) { _have_search_terms_ = true; search_terms_ = value; } /** * Clears the '<code>textFormat</code>' attribute so it is no longer set. */ void clear_text_format() { _have_text_format_ = false; client::ClearCppValueHelper(&text_format_); } /** * Gets the optional '<code>textFormat</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_text_format() const { return text_format_; } /** * Gets a modifiable pointer to the optional <code>textFormat</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_textFormat() { _have_text_format_ = true; return &text_format_; } /** * Sets the '<code>textFormat</code>' attribute. * * @param[in] value Set this parameter's value to html or plainText to * instruct the API to return the comments left by users in html formatted * or in plain text. */ void set_text_format(const string& value) { _have_text_format_ = true; text_format_ = value; } /** * Clears the '<code>videoId</code>' attribute so it is no longer set. */ void clear_video_id() { _have_video_id_ = false; client::ClearCppValueHelper(&video_id_); } /** * Gets the optional '<code>videoId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_video_id() const { return video_id_; } /** * Gets a modifiable pointer to the optional <code>videoId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_videoId() { _have_video_id_ = true; return &video_id_; } /** * Sets the '<code>videoId</code>' attribute. * * @param[in] value The videoId parameter instructs the API to return * comment threads associated with the specified video ID. */ void set_video_id(const string& value) { _have_video_id_ = true; video_id_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( CommentThreadListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string all_threads_related_to_channel_id_; string channel_id_; string id_; uint32 max_results_; string moderation_status_; string order_; string page_token_; string search_terms_; string text_format_; string video_id_; bool _have_all_threads_related_to_channel_id_ : 1; bool _have_channel_id_ : 1; bool _have_id_ : 1; bool _have_max_results_ : 1; bool _have_moderation_status_ : 1; bool _have_order_ : 1; bool _have_page_token_ : 1; bool _have_search_terms_ : 1; bool _have_text_format_ : 1; bool _have_video_id_ : 1; DISALLOW_COPY_AND_ASSIGN(CommentThreadsResource_ListMethod); }; typedef client::ServiceRequestPager< CommentThreadsResource_ListMethod, CommentThreadListResponse> CommentThreadsResource_ListMethodPager; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube.force-ssl */ class CommentThreadsResource_UpdateMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies a comma-separated list of * commentThread resource properties that the API response will include. You * must at least include the snippet part in the parameter value since that * part contains all of the properties that the API request can update. * @param[in] _content_ The data object to update. */ CommentThreadsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const CommentThread& _content_); /** * Standard destructor. */ virtual ~CommentThreadsResource_UpdateMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( CommentThread* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string _content_; DISALLOW_COPY_AND_ASSIGN(CommentThreadsResource_UpdateMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube.force-ssl */ class CommentsResource_DeleteMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter specifies the comment ID for the resource * that is being deleted. */ CommentsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id); /** * Standard destructor. */ virtual ~CommentsResource_DeleteMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string id_; DISALLOW_COPY_AND_ASSIGN(CommentsResource_DeleteMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube.force-ssl */ class CommentsResource_InsertMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter identifies the properties that the API * response will include. Set the parameter value to snippet. The snippet part * has a quota cost of 2 units. * @param[in] _content_ The data object to insert. */ CommentsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Comment& _content_); /** * Standard destructor. */ virtual ~CommentsResource_InsertMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Comment* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string _content_; DISALLOW_COPY_AND_ASSIGN(CommentsResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube.force-ssl */ class CommentsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies a comma-separated list of one * or more comment resource properties that the API response will include. */ CommentsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~CommentsResource_ListMethod(); /** * Clears the '<code>id</code>' attribute so it is no longer set. */ void clear_id() { _have_id_ = false; client::ClearCppValueHelper(&id_); } /** * Gets the optional '<code>id</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_id() const { return id_; } /** * Gets a modifiable pointer to the optional <code>id</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_id() { _have_id_ = true; return &id_; } /** * Sets the '<code>id</code>' attribute. * * @param[in] value The id parameter specifies a comma-separated list of * comment IDs for the resources that are being retrieved. In a comment * resource, the id property specifies the comment's ID. */ void set_id(const string& value) { _have_id_ = true; id_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * items that should be returned in the result set. * * Note: This parameter is not supported for use in conjunction with the id * parameter. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken property identifies the next page of the result that can be * retrieved. * * Note: This parameter is not supported for use in conjunction with the id * parameter. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Clears the '<code>parentId</code>' attribute so it is no longer set. */ void clear_parent_id() { _have_parent_id_ = false; client::ClearCppValueHelper(&parent_id_); } /** * Gets the optional '<code>parentId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_parent_id() const { return parent_id_; } /** * Gets a modifiable pointer to the optional <code>parentId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_parentId() { _have_parent_id_ = true; return &parent_id_; } /** * Sets the '<code>parentId</code>' attribute. * * @param[in] value The parentId parameter specifies the ID of the comment * for which replies should be retrieved. * * Note: YouTube currently supports replies only for top-level comments. * However, replies to replies may be supported in the future. */ void set_parent_id(const string& value) { _have_parent_id_ = true; parent_id_ = value; } /** * Clears the '<code>textFormat</code>' attribute so it is no longer set. */ void clear_text_format() { _have_text_format_ = false; client::ClearCppValueHelper(&text_format_); } /** * Gets the optional '<code>textFormat</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_text_format() const { return text_format_; } /** * Gets a modifiable pointer to the optional <code>textFormat</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_textFormat() { _have_text_format_ = true; return &text_format_; } /** * Sets the '<code>textFormat</code>' attribute. * * @param[in] value This parameter indicates whether the API should return * comments formatted as HTML or as plain text. */ void set_text_format(const string& value) { _have_text_format_ = true; text_format_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( CommentListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string id_; uint32 max_results_; string page_token_; string parent_id_; string text_format_; bool _have_id_ : 1; bool _have_max_results_ : 1; bool _have_page_token_ : 1; bool _have_parent_id_ : 1; bool _have_text_format_ : 1; DISALLOW_COPY_AND_ASSIGN(CommentsResource_ListMethod); }; typedef client::ServiceRequestPager< CommentsResource_ListMethod, CommentListResponse> CommentsResource_ListMethodPager; /** * Implements the markAsSpam method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube.force-ssl */ class CommentsResource_MarkAsSpamMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter specifies a comma-separated list of IDs of * comments that the caller believes should be classified as spam. */ CommentsResource_MarkAsSpamMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id); /** * Standard destructor. */ virtual ~CommentsResource_MarkAsSpamMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string id_; DISALLOW_COPY_AND_ASSIGN(CommentsResource_MarkAsSpamMethod); }; /** * Implements the setModerationStatus method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube.force-ssl */ class CommentsResource_SetModerationStatusMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter specifies a comma-separated list of IDs that * identify the comments for which you are updating the moderation status. * @param[in] moderation_status Identifies the new moderation status of the * specified comments. */ CommentsResource_SetModerationStatusMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& moderation_status); /** * Standard destructor. */ virtual ~CommentsResource_SetModerationStatusMethod(); /** * Clears the '<code>banAuthor</code>' attribute so it is no longer set. */ void clear_ban_author() { _have_ban_author_ = false; client::ClearCppValueHelper(&ban_author_); } /** * Gets the optional '<code>banAuthor</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_ban_author() const { return ban_author_; } /** * Sets the '<code>banAuthor</code>' attribute. * * @param[in] value The banAuthor parameter lets you indicate that you want * to automatically reject any additional comments written by the comment's * author. Set the parameter value to true to ban the author. * * Note: This parameter is only valid if the moderationStatus parameter is * also set to rejected. */ void set_ban_author(bool value) { _have_ban_author_ = true; ban_author_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string id_; string moderation_status_; bool ban_author_; bool _have_ban_author_ : 1; DISALLOW_COPY_AND_ASSIGN(CommentsResource_SetModerationStatusMethod); }; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube.force-ssl */ class CommentsResource_UpdateMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter identifies the properties that the API * response will include. You must at least include the snippet part in the * parameter value since that part contains all of the properties that the API * request can update. * @param[in] _content_ The data object to update. */ CommentsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Comment& _content_); /** * Standard destructor. */ virtual ~CommentsResource_UpdateMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Comment* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string _content_; DISALLOW_COPY_AND_ASSIGN(CommentsResource_UpdateMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly */ class FanFundingEventsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies the fanFundingEvent resource * parts that the API response will include. Supported values are id and * snippet. */ FanFundingEventsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~FanFundingEventsResource_ListMethod(); /** * Clears the '<code>hl</code>' attribute so it is no longer set. */ void clear_hl() { _have_hl_ = false; client::ClearCppValueHelper(&hl_); } /** * Gets the optional '<code>hl</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_hl() const { return hl_; } /** * Gets a modifiable pointer to the optional <code>hl</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_hl() { _have_hl_ = true; return &hl_; } /** * Sets the '<code>hl</code>' attribute. * * @param[in] value The hl parameter instructs the API to retrieve localized * resource metadata for a specific application language that the YouTube * website supports. The parameter value must be a language code included in * the list returned by the i18nLanguages.list method. * * If localized resource details are available in that language, the * resource's snippet.localized object will contain the localized values. * However, if localized details are not available, the snippet.localized * object will contain resource details in the resource's default language. */ void set_hl(const string& value) { _have_hl_ = true; hl_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * items that should be returned in the result set. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken and prevPageToken properties identify other pages that * could be retrieved. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( FanFundingEventListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string hl_; uint32 max_results_; string page_token_; bool _have_hl_ : 1; bool _have_max_results_ : 1; bool _have_page_token_ : 1; DISALLOW_COPY_AND_ASSIGN(FanFundingEventsResource_ListMethod); }; typedef client::ServiceRequestPager< FanFundingEventsResource_ListMethod, FanFundingEventListResponse> FanFundingEventsResource_ListMethodPager; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly * https://www.googleapis.com/auth/youtubepartner */ class GuideCategoriesResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies the guideCategory resource * properties that the API response will include. Set the parameter value to * snippet. */ GuideCategoriesResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~GuideCategoriesResource_ListMethod(); /** * Clears the '<code>hl</code>' attribute so it is no longer set. */ void clear_hl() { _have_hl_ = false; client::ClearCppValueHelper(&hl_); } /** * Gets the optional '<code>hl</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_hl() const { return hl_; } /** * Gets a modifiable pointer to the optional <code>hl</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_hl() { _have_hl_ = true; return &hl_; } /** * Sets the '<code>hl</code>' attribute. * * @param[in] value The hl parameter specifies the language that will be * used for text values in the API response. */ void set_hl(const string& value) { _have_hl_ = true; hl_ = value; } /** * Clears the '<code>id</code>' attribute so it is no longer set. */ void clear_id() { _have_id_ = false; client::ClearCppValueHelper(&id_); } /** * Gets the optional '<code>id</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_id() const { return id_; } /** * Gets a modifiable pointer to the optional <code>id</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_id() { _have_id_ = true; return &id_; } /** * Sets the '<code>id</code>' attribute. * * @param[in] value The id parameter specifies a comma-separated list of the * YouTube channel category ID(s) for the resource(s) that are being * retrieved. In a guideCategory resource, the id property specifies the * YouTube channel category ID. */ void set_id(const string& value) { _have_id_ = true; id_ = value; } /** * Clears the '<code>regionCode</code>' attribute so it is no longer set. */ void clear_region_code() { _have_region_code_ = false; client::ClearCppValueHelper(&region_code_); } /** * Gets the optional '<code>regionCode</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_region_code() const { return region_code_; } /** * Gets a modifiable pointer to the optional <code>regionCode</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_regionCode() { _have_region_code_ = true; return &region_code_; } /** * Sets the '<code>regionCode</code>' attribute. * * @param[in] value The regionCode parameter instructs the API to return the * list of guide categories available in the specified country. The * parameter value is an ISO 3166-1 alpha-2 country code. */ void set_region_code(const string& value) { _have_region_code_ = true; region_code_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( GuideCategoryListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string hl_; string id_; string region_code_; bool _have_hl_ : 1; bool _have_id_ : 1; bool _have_region_code_ : 1; DISALLOW_COPY_AND_ASSIGN(GuideCategoriesResource_ListMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly * https://www.googleapis.com/auth/youtubepartner */ class I18nLanguagesResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies the i18nLanguage resource * properties that the API response will include. Set the parameter value to * snippet. */ I18nLanguagesResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~I18nLanguagesResource_ListMethod(); /** * Clears the '<code>hl</code>' attribute so it is no longer set. */ void clear_hl() { _have_hl_ = false; client::ClearCppValueHelper(&hl_); } /** * Gets the optional '<code>hl</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_hl() const { return hl_; } /** * Gets a modifiable pointer to the optional <code>hl</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_hl() { _have_hl_ = true; return &hl_; } /** * Sets the '<code>hl</code>' attribute. * * @param[in] value The hl parameter specifies the language that should be * used for text values in the API response. */ void set_hl(const string& value) { _have_hl_ = true; hl_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( I18nLanguageListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string hl_; bool _have_hl_ : 1; DISALLOW_COPY_AND_ASSIGN(I18nLanguagesResource_ListMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly * https://www.googleapis.com/auth/youtubepartner */ class I18nRegionsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies the i18nRegion resource * properties that the API response will include. Set the parameter value to * snippet. */ I18nRegionsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~I18nRegionsResource_ListMethod(); /** * Clears the '<code>hl</code>' attribute so it is no longer set. */ void clear_hl() { _have_hl_ = false; client::ClearCppValueHelper(&hl_); } /** * Gets the optional '<code>hl</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_hl() const { return hl_; } /** * Gets a modifiable pointer to the optional <code>hl</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_hl() { _have_hl_ = true; return &hl_; } /** * Sets the '<code>hl</code>' attribute. * * @param[in] value The hl parameter specifies the language that should be * used for text values in the API response. */ void set_hl(const string& value) { _have_hl_ = true; hl_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( I18nRegionListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string hl_; bool _have_hl_ : 1; DISALLOW_COPY_AND_ASSIGN(I18nRegionsResource_ListMethod); }; /** * Implements the bind method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class LiveBroadcastsResource_BindMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter specifies the unique ID of the broadcast * that is being bound to a video stream. * @param[in] part The part parameter specifies a comma-separated list of one * or more liveBroadcast resource properties that the API response will * include. The part names that you can include in the parameter value are id, * snippet, contentDetails, and status. */ LiveBroadcastsResource_BindMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& part); /** * Standard destructor. */ virtual ~LiveBroadcastsResource_BindMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Clears the '<code>streamId</code>' attribute so it is no longer set. */ void clear_stream_id() { _have_stream_id_ = false; client::ClearCppValueHelper(&stream_id_); } /** * Gets the optional '<code>streamId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_stream_id() const { return stream_id_; } /** * Gets a modifiable pointer to the optional <code>streamId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_streamId() { _have_stream_id_ = true; return &stream_id_; } /** * Sets the '<code>streamId</code>' attribute. * * @param[in] value The streamId parameter specifies the unique ID of the * video stream that is being bound to a broadcast. If this parameter is * omitted, the API will remove any existing binding between the broadcast * and a video stream. */ void set_stream_id(const string& value) { _have_stream_id_ = true; stream_id_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( LiveBroadcast* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string id_; string part_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; string stream_id_; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; bool _have_stream_id_ : 1; DISALLOW_COPY_AND_ASSIGN(LiveBroadcastsResource_BindMethod); }; /** * Implements the control method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class LiveBroadcastsResource_ControlMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter specifies the YouTube live broadcast ID that * uniquely identifies the broadcast in which the slate is being updated. * @param[in] part The part parameter specifies a comma-separated list of one * or more liveBroadcast resource properties that the API response will * include. The part names that you can include in the parameter value are id, * snippet, contentDetails, and status. */ LiveBroadcastsResource_ControlMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& part); /** * Standard destructor. */ virtual ~LiveBroadcastsResource_ControlMethod(); /** * Clears the '<code>displaySlate</code>' attribute so it is no longer set. */ void clear_display_slate() { _have_display_slate_ = false; client::ClearCppValueHelper(&display_slate_); } /** * Gets the optional '<code>displaySlate</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_display_slate() const { return display_slate_; } /** * Sets the '<code>displaySlate</code>' attribute. * * @param[in] value The displaySlate parameter specifies whether the slate * is being enabled or disabled. */ void set_display_slate(bool value) { _have_display_slate_ = true; display_slate_ = value; } /** * Clears the '<code>offsetTimeMs</code>' attribute so it is no longer set. */ void clear_offset_time_ms() { _have_offset_time_ms_ = false; client::ClearCppValueHelper(&offset_time_ms_); } /** * Gets the optional '<code>offsetTimeMs</code>' attribute. * * If the value is not set then the default value will be returned. */ uint64 get_offset_time_ms() const { return offset_time_ms_; } /** * Sets the '<code>offsetTimeMs</code>' attribute. * * @param[in] value The offsetTimeMs parameter specifies a positive time * offset when the specified slate change will occur. The value is measured * in milliseconds from the beginning of the broadcast's monitor stream, * which is the time that the testing phase for the broadcast began. Even * though it is specified in milliseconds, the value is actually an * approximation, and YouTube completes the requested action as closely as * possible to that time. * * If you do not specify a value for this parameter, then YouTube performs * the action as soon as possible. See the Getting started guide for more * details. * * Important: You should only specify a value for this parameter if your * broadcast stream is delayed. */ void set_offset_time_ms(uint64 value) { _have_offset_time_ms_ = true; offset_time_ms_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Clears the '<code>walltime</code>' attribute so it is no longer set. */ void clear_walltime() { _have_walltime_ = false; client::ClearCppValueHelper(&walltime_); } /** * Gets the optional '<code>walltime</code>' attribute. * * If the value is not set then the default value will be returned. */ client::DateTime get_walltime() const { return walltime_; } /** * Sets the '<code>walltime</code>' attribute. * * @param[in] value The walltime parameter specifies the wall clock time at * which the specified slate change will occur. The value is specified in * ISO 8601 (YYYY-MM-DDThh:mm:ss.sssZ) format. */ void set_walltime(client::DateTime value) { _have_walltime_ = true; walltime_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( LiveBroadcast* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string id_; string part_; bool display_slate_; uint64 offset_time_ms_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; client::DateTime walltime_; bool _have_display_slate_ : 1; bool _have_offset_time_ms_ : 1; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; bool _have_walltime_ : 1; DISALLOW_COPY_AND_ASSIGN(LiveBroadcastsResource_ControlMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class LiveBroadcastsResource_DeleteMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter specifies the YouTube live broadcast ID for * the resource that is being deleted. */ LiveBroadcastsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id); /** * Standard destructor. */ virtual ~LiveBroadcastsResource_DeleteMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string id_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; DISALLOW_COPY_AND_ASSIGN(LiveBroadcastsResource_DeleteMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class LiveBroadcastsResource_InsertMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * The part properties that you can include in the parameter value are id, * snippet, contentDetails, and status. * @param[in] _content_ The data object to insert. */ LiveBroadcastsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveBroadcast& _content_); /** * Standard destructor. */ virtual ~LiveBroadcastsResource_InsertMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( LiveBroadcast* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(LiveBroadcastsResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly */ class LiveBroadcastsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies a comma-separated list of one * or more liveBroadcast resource properties that the API response will * include. The part names that you can include in the parameter value are id, * snippet, contentDetails, and status. */ LiveBroadcastsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~LiveBroadcastsResource_ListMethod(); /** * Clears the '<code>broadcastStatus</code>' attribute so it is no longer * set. */ void clear_broadcast_status() { _have_broadcast_status_ = false; client::ClearCppValueHelper(&broadcast_status_); } /** * Gets the optional '<code>broadcastStatus</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_broadcast_status() const { return broadcast_status_; } /** * Gets a modifiable pointer to the optional <code>broadcastStatus</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_broadcastStatus() { _have_broadcast_status_ = true; return &broadcast_status_; } /** * Sets the '<code>broadcastStatus</code>' attribute. * * @param[in] value The broadcastStatus parameter filters the API response * to only include broadcasts with the specified status. */ void set_broadcast_status(const string& value) { _have_broadcast_status_ = true; broadcast_status_ = value; } /** * Clears the '<code>broadcastType</code>' attribute so it is no longer set. */ void clear_broadcast_type() { _have_broadcast_type_ = false; client::ClearCppValueHelper(&broadcast_type_); } /** * Gets the optional '<code>broadcastType</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_broadcast_type() const { return broadcast_type_; } /** * Gets a modifiable pointer to the optional <code>broadcastType</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_broadcastType() { _have_broadcast_type_ = true; return &broadcast_type_; } /** * Sets the '<code>broadcastType</code>' attribute. * * @param[in] value The broadcastType parameter filters the API response to * only include broadcasts with the specified type. This is only compatible * with the mine filter for now. */ void set_broadcast_type(const string& value) { _have_broadcast_type_ = true; broadcast_type_ = value; } /** * Clears the '<code>id</code>' attribute so it is no longer set. */ void clear_id() { _have_id_ = false; client::ClearCppValueHelper(&id_); } /** * Gets the optional '<code>id</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_id() const { return id_; } /** * Gets a modifiable pointer to the optional <code>id</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_id() { _have_id_ = true; return &id_; } /** * Sets the '<code>id</code>' attribute. * * @param[in] value The id parameter specifies a comma-separated list of * YouTube broadcast IDs that identify the broadcasts being retrieved. In a * liveBroadcast resource, the id property specifies the broadcast's ID. */ void set_id(const string& value) { _have_id_ = true; id_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * items that should be returned in the result set. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>mine</code>' attribute so it is no longer set. */ void clear_mine() { _have_mine_ = false; client::ClearCppValueHelper(&mine_); } /** * Gets the optional '<code>mine</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_mine() const { return mine_; } /** * Sets the '<code>mine</code>' attribute. * * @param[in] value The mine parameter can be used to instruct the API to * only return broadcasts owned by the authenticated user. Set the parameter * value to true to only retrieve your own broadcasts. */ void set_mine(bool value) { _have_mine_ = true; mine_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken and prevPageToken properties identify other pages that * could be retrieved. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( LiveBroadcastListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string broadcast_status_; string broadcast_type_; string id_; uint32 max_results_; bool mine_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; string page_token_; bool _have_broadcast_status_ : 1; bool _have_broadcast_type_ : 1; bool _have_id_ : 1; bool _have_max_results_ : 1; bool _have_mine_ : 1; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; bool _have_page_token_ : 1; DISALLOW_COPY_AND_ASSIGN(LiveBroadcastsResource_ListMethod); }; typedef client::ServiceRequestPager< LiveBroadcastsResource_ListMethod, LiveBroadcastListResponse> LiveBroadcastsResource_ListMethodPager; /** * Implements the transition method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class LiveBroadcastsResource_TransitionMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] broadcast_status The broadcastStatus parameter identifies the * state to which the broadcast is changing. Note that to transition a * broadcast to either the testing or live state, the status.streamStatus must * be active for the stream that the broadcast is bound to. * @param[in] id The id parameter specifies the unique ID of the broadcast * that is transitioning to another status. * @param[in] part The part parameter specifies a comma-separated list of one * or more liveBroadcast resource properties that the API response will * include. The part names that you can include in the parameter value are id, * snippet, contentDetails, and status. */ LiveBroadcastsResource_TransitionMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& broadcast_status, const StringPiece& id, const StringPiece& part); /** * Standard destructor. */ virtual ~LiveBroadcastsResource_TransitionMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( LiveBroadcast* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string broadcast_status_; string id_; string part_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; DISALLOW_COPY_AND_ASSIGN(LiveBroadcastsResource_TransitionMethod); }; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class LiveBroadcastsResource_UpdateMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * The part properties that you can include in the parameter value are id, * snippet, contentDetails, and status. * * Note that this method will override the existing values for all of the * mutable properties that are contained in any parts that the parameter value * specifies. For example, a broadcast's privacy status is defined in the * status part. As such, if your request is updating a private or unlisted * broadcast, and the request's part parameter value includes the status part, * the broadcast's privacy setting will be updated to whatever value the * request body specifies. If the request body does not specify a value, the * existing privacy setting will be removed and the broadcast will revert to * the default privacy setting. * @param[in] _content_ The data object to update. */ LiveBroadcastsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveBroadcast& _content_); /** * Standard destructor. */ virtual ~LiveBroadcastsResource_UpdateMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( LiveBroadcast* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(LiveBroadcastsResource_UpdateMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class LiveChatBansResource_DeleteMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter identifies the chat ban to remove. The value * uniquely identifies both the ban and the chat. */ LiveChatBansResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id); /** * Standard destructor. */ virtual ~LiveChatBansResource_DeleteMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string id_; DISALLOW_COPY_AND_ASSIGN(LiveChatBansResource_DeleteMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class LiveChatBansResource_InsertMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response returns. Set the parameter value to * snippet. * @param[in] _content_ The data object to insert. */ LiveChatBansResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveChatBan& _content_); /** * Standard destructor. */ virtual ~LiveChatBansResource_InsertMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( LiveChatBan* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string _content_; DISALLOW_COPY_AND_ASSIGN(LiveChatBansResource_InsertMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class LiveChatMessagesResource_DeleteMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter specifies the YouTube chat message ID of the * resource that is being deleted. */ LiveChatMessagesResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id); /** * Standard destructor. */ virtual ~LiveChatMessagesResource_DeleteMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string id_; DISALLOW_COPY_AND_ASSIGN(LiveChatMessagesResource_DeleteMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class LiveChatMessagesResource_InsertMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes. It identifies the * properties that the write operation will set as well as the properties that * the API response will include. Set the parameter value to snippet. * @param[in] _content_ The data object to insert. */ LiveChatMessagesResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveChatMessage& _content_); /** * Standard destructor. */ virtual ~LiveChatMessagesResource_InsertMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( LiveChatMessage* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string _content_; DISALLOW_COPY_AND_ASSIGN(LiveChatMessagesResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly */ class LiveChatMessagesResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] live_chat_id The liveChatId parameter specifies the ID of the * chat whose messages will be returned. * @param[in] part The part parameter specifies the liveChatComment resource * parts that the API response will include. Supported values are id and * snippet. */ LiveChatMessagesResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& live_chat_id, const StringPiece& part); /** * Standard destructor. */ virtual ~LiveChatMessagesResource_ListMethod(); /** * Clears the '<code>hl</code>' attribute so it is no longer set. */ void clear_hl() { _have_hl_ = false; client::ClearCppValueHelper(&hl_); } /** * Gets the optional '<code>hl</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_hl() const { return hl_; } /** * Gets a modifiable pointer to the optional <code>hl</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_hl() { _have_hl_ = true; return &hl_; } /** * Sets the '<code>hl</code>' attribute. * * @param[in] value The hl parameter instructs the API to retrieve localized * resource metadata for a specific application language that the YouTube * website supports. The parameter value must be a language code included in * the list returned by the i18nLanguages.list method. * * If localized resource details are available in that language, the * resource's snippet.localized object will contain the localized values. * However, if localized details are not available, the snippet.localized * object will contain resource details in the resource's default language. */ void set_hl(const string& value) { _have_hl_ = true; hl_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * messages that should be returned in the result set. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken property identify other pages that could be retrieved. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Clears the '<code>profileImageSize</code>' attribute so it is no longer * set. */ void clear_profile_image_size() { _have_profile_image_size_ = false; client::ClearCppValueHelper(&profile_image_size_); } /** * Gets the optional '<code>profileImageSize</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_profile_image_size() const { return profile_image_size_; } /** * Sets the '<code>profileImageSize</code>' attribute. * * @param[in] value The profileImageSize parameter specifies the size of the * user profile pictures that should be returned in the result set. Default: * 88. */ void set_profile_image_size(uint32 value) { _have_profile_image_size_ = true; profile_image_size_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( LiveChatMessageListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string live_chat_id_; string part_; string hl_; uint32 max_results_; string page_token_; uint32 profile_image_size_; bool _have_hl_ : 1; bool _have_max_results_ : 1; bool _have_page_token_ : 1; bool _have_profile_image_size_ : 1; DISALLOW_COPY_AND_ASSIGN(LiveChatMessagesResource_ListMethod); }; typedef client::ServiceRequestPager< LiveChatMessagesResource_ListMethod, LiveChatMessageListResponse> LiveChatMessagesResource_ListMethodPager; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class LiveChatModeratorsResource_DeleteMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter identifies the chat moderator to remove. The * value uniquely identifies both the moderator and the chat. */ LiveChatModeratorsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id); /** * Standard destructor. */ virtual ~LiveChatModeratorsResource_DeleteMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string id_; DISALLOW_COPY_AND_ASSIGN(LiveChatModeratorsResource_DeleteMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class LiveChatModeratorsResource_InsertMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response returns. Set the parameter value to * snippet. * @param[in] _content_ The data object to insert. */ LiveChatModeratorsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveChatModerator& _content_); /** * Standard destructor. */ virtual ~LiveChatModeratorsResource_InsertMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( LiveChatModerator* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string _content_; DISALLOW_COPY_AND_ASSIGN(LiveChatModeratorsResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly */ class LiveChatModeratorsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] live_chat_id The liveChatId parameter specifies the YouTube live * chat for which the API should return moderators. * @param[in] part The part parameter specifies the liveChatModerator resource * parts that the API response will include. Supported values are id and * snippet. */ LiveChatModeratorsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& live_chat_id, const StringPiece& part); /** * Standard destructor. */ virtual ~LiveChatModeratorsResource_ListMethod(); /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * items that should be returned in the result set. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken and prevPageToken properties identify other pages that * could be retrieved. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( LiveChatModeratorListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string live_chat_id_; string part_; uint32 max_results_; string page_token_; bool _have_max_results_ : 1; bool _have_page_token_ : 1; DISALLOW_COPY_AND_ASSIGN(LiveChatModeratorsResource_ListMethod); }; typedef client::ServiceRequestPager< LiveChatModeratorsResource_ListMethod, LiveChatModeratorListResponse> LiveChatModeratorsResource_ListMethodPager; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class LiveStreamsResource_DeleteMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter specifies the YouTube live stream ID for the * resource that is being deleted. */ LiveStreamsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id); /** * Standard destructor. */ virtual ~LiveStreamsResource_DeleteMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string id_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; DISALLOW_COPY_AND_ASSIGN(LiveStreamsResource_DeleteMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class LiveStreamsResource_InsertMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * The part properties that you can include in the parameter value are id, * snippet, cdn, and status. * @param[in] _content_ The data object to insert. */ LiveStreamsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveStream& _content_); /** * Standard destructor. */ virtual ~LiveStreamsResource_InsertMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( LiveStream* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(LiveStreamsResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly */ class LiveStreamsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies a comma-separated list of one * or more liveStream resource properties that the API response will include. * The part names that you can include in the parameter value are id, snippet, * cdn, and status. */ LiveStreamsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~LiveStreamsResource_ListMethod(); /** * Clears the '<code>id</code>' attribute so it is no longer set. */ void clear_id() { _have_id_ = false; client::ClearCppValueHelper(&id_); } /** * Gets the optional '<code>id</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_id() const { return id_; } /** * Gets a modifiable pointer to the optional <code>id</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_id() { _have_id_ = true; return &id_; } /** * Sets the '<code>id</code>' attribute. * * @param[in] value The id parameter specifies a comma-separated list of * YouTube stream IDs that identify the streams being retrieved. In a * liveStream resource, the id property specifies the stream's ID. */ void set_id(const string& value) { _have_id_ = true; id_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * items that should be returned in the result set. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>mine</code>' attribute so it is no longer set. */ void clear_mine() { _have_mine_ = false; client::ClearCppValueHelper(&mine_); } /** * Gets the optional '<code>mine</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_mine() const { return mine_; } /** * Sets the '<code>mine</code>' attribute. * * @param[in] value The mine parameter can be used to instruct the API to * only return streams owned by the authenticated user. Set the parameter * value to true to only retrieve your own streams. */ void set_mine(bool value) { _have_mine_ = true; mine_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken and prevPageToken properties identify other pages that * could be retrieved. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( LiveStreamListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string id_; uint32 max_results_; bool mine_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; string page_token_; bool _have_id_ : 1; bool _have_max_results_ : 1; bool _have_mine_ : 1; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; bool _have_page_token_ : 1; DISALLOW_COPY_AND_ASSIGN(LiveStreamsResource_ListMethod); }; typedef client::ServiceRequestPager< LiveStreamsResource_ListMethod, LiveStreamListResponse> LiveStreamsResource_ListMethodPager; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl */ class LiveStreamsResource_UpdateMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * The part properties that you can include in the parameter value are id, * snippet, cdn, and status. * * Note that this method will override the existing values for all of the * mutable properties that are contained in any parts that the parameter value * specifies. If the request body does not specify a value for a mutable * property, the existing value for that property will be removed. * @param[in] _content_ The data object to update. */ LiveStreamsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveStream& _content_); /** * Standard destructor. */ virtual ~LiveStreamsResource_UpdateMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( LiveStream* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(LiveStreamsResource_UpdateMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class PlaylistItemsResource_DeleteMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter specifies the YouTube playlist item ID for * the playlist item that is being deleted. In a playlistItem resource, the id * property specifies the playlist item's ID. */ PlaylistItemsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id); /** * Standard destructor. */ virtual ~PlaylistItemsResource_DeleteMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string id_; string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; DISALLOW_COPY_AND_ASSIGN(PlaylistItemsResource_DeleteMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class PlaylistItemsResource_InsertMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * @param[in] _content_ The data object to insert. */ PlaylistItemsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const PlaylistItem& _content_); /** * Standard destructor. */ virtual ~PlaylistItemsResource_InsertMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( PlaylistItem* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(PlaylistItemsResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly * https://www.googleapis.com/auth/youtubepartner */ class PlaylistItemsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies a comma-separated list of one * or more playlistItem resource properties that the API response will * include. * * If the parameter identifies a property that contains child properties, the * child properties will be included in the response. For example, in a * playlistItem resource, the snippet property contains numerous fields, * including the title, description, position, and resourceId properties. As * such, if you set part=snippet, the API response will contain all of those * properties. */ PlaylistItemsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~PlaylistItemsResource_ListMethod(); /** * Clears the '<code>id</code>' attribute so it is no longer set. */ void clear_id() { _have_id_ = false; client::ClearCppValueHelper(&id_); } /** * Gets the optional '<code>id</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_id() const { return id_; } /** * Gets a modifiable pointer to the optional <code>id</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_id() { _have_id_ = true; return &id_; } /** * Sets the '<code>id</code>' attribute. * * @param[in] value The id parameter specifies a comma-separated list of one * or more unique playlist item IDs. */ void set_id(const string& value) { _have_id_ = true; id_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * items that should be returned in the result set. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken and prevPageToken properties identify other pages that * could be retrieved. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Clears the '<code>playlistId</code>' attribute so it is no longer set. */ void clear_playlist_id() { _have_playlist_id_ = false; client::ClearCppValueHelper(&playlist_id_); } /** * Gets the optional '<code>playlistId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_playlist_id() const { return playlist_id_; } /** * Gets a modifiable pointer to the optional <code>playlistId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_playlistId() { _have_playlist_id_ = true; return &playlist_id_; } /** * Sets the '<code>playlistId</code>' attribute. * * @param[in] value The playlistId parameter specifies the unique ID of the * playlist for which you want to retrieve playlist items. Note that even * though this is an optional parameter, every request to retrieve playlist * items must specify a value for either the id parameter or the playlistId * parameter. */ void set_playlist_id(const string& value) { _have_playlist_id_ = true; playlist_id_ = value; } /** * Clears the '<code>videoId</code>' attribute so it is no longer set. */ void clear_video_id() { _have_video_id_ = false; client::ClearCppValueHelper(&video_id_); } /** * Gets the optional '<code>videoId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_video_id() const { return video_id_; } /** * Gets a modifiable pointer to the optional <code>videoId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_videoId() { _have_video_id_ = true; return &video_id_; } /** * Sets the '<code>videoId</code>' attribute. * * @param[in] value The videoId parameter specifies that the request should * return only the playlist items that contain the specified video. */ void set_video_id(const string& value) { _have_video_id_ = true; video_id_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( PlaylistItemListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string id_; uint32 max_results_; string on_behalf_of_content_owner_; string page_token_; string playlist_id_; string video_id_; bool _have_id_ : 1; bool _have_max_results_ : 1; bool _have_on_behalf_of_content_owner_ : 1; bool _have_page_token_ : 1; bool _have_playlist_id_ : 1; bool _have_video_id_ : 1; DISALLOW_COPY_AND_ASSIGN(PlaylistItemsResource_ListMethod); }; typedef client::ServiceRequestPager< PlaylistItemsResource_ListMethod, PlaylistItemListResponse> PlaylistItemsResource_ListMethodPager; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class PlaylistItemsResource_UpdateMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * Note that this method will override the existing values for all of the * mutable properties that are contained in any parts that the parameter value * specifies. For example, a playlist item can specify a start time and end * time, which identify the times portion of the video that should play when * users watch the video in the playlist. If your request is updating a * playlist item that sets these values, and the request's part parameter * value includes the contentDetails part, the playlist item's start and end * times will be updated to whatever value the request body specifies. If the * request body does not specify values, the existing start and end times will * be removed and replaced with the default settings. * @param[in] _content_ The data object to update. */ PlaylistItemsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const PlaylistItem& _content_); /** * Standard destructor. */ virtual ~PlaylistItemsResource_UpdateMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( PlaylistItem* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(PlaylistItemsResource_UpdateMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class PlaylistsResource_DeleteMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter specifies the YouTube playlist ID for the * playlist that is being deleted. In a playlist resource, the id property * specifies the playlist's ID. */ PlaylistsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id); /** * Standard destructor. */ virtual ~PlaylistsResource_DeleteMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string id_; string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; DISALLOW_COPY_AND_ASSIGN(PlaylistsResource_DeleteMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class PlaylistsResource_InsertMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * @param[in] _content_ The data object to insert. */ PlaylistsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Playlist& _content_); /** * Standard destructor. */ virtual ~PlaylistsResource_InsertMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Playlist* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(PlaylistsResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly * https://www.googleapis.com/auth/youtubepartner */ class PlaylistsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies a comma-separated list of one * or more playlist resource properties that the API response will include. * * If the parameter identifies a property that contains child properties, the * child properties will be included in the response. For example, in a * playlist resource, the snippet property contains properties like author, * title, description, tags, and timeCreated. As such, if you set * part=snippet, the API response will contain all of those properties. */ PlaylistsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~PlaylistsResource_ListMethod(); /** * Clears the '<code>channelId</code>' attribute so it is no longer set. */ void clear_channel_id() { _have_channel_id_ = false; client::ClearCppValueHelper(&channel_id_); } /** * Gets the optional '<code>channelId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_channel_id() const { return channel_id_; } /** * Gets a modifiable pointer to the optional <code>channelId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_channelId() { _have_channel_id_ = true; return &channel_id_; } /** * Sets the '<code>channelId</code>' attribute. * * @param[in] value This value indicates that the API should only return the * specified channel's playlists. */ void set_channel_id(const string& value) { _have_channel_id_ = true; channel_id_ = value; } /** * Clears the '<code>hl</code>' attribute so it is no longer set. */ void clear_hl() { _have_hl_ = false; client::ClearCppValueHelper(&hl_); } /** * Gets the optional '<code>hl</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_hl() const { return hl_; } /** * Gets a modifiable pointer to the optional <code>hl</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_hl() { _have_hl_ = true; return &hl_; } /** * Sets the '<code>hl</code>' attribute. * * @param[in] value The hl parameter should be used for filter out the * properties that are not in the given language. Used for the snippet part. */ void set_hl(const string& value) { _have_hl_ = true; hl_ = value; } /** * Clears the '<code>id</code>' attribute so it is no longer set. */ void clear_id() { _have_id_ = false; client::ClearCppValueHelper(&id_); } /** * Gets the optional '<code>id</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_id() const { return id_; } /** * Gets a modifiable pointer to the optional <code>id</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_id() { _have_id_ = true; return &id_; } /** * Sets the '<code>id</code>' attribute. * * @param[in] value The id parameter specifies a comma-separated list of the * YouTube playlist ID(s) for the resource(s) that are being retrieved. In a * playlist resource, the id property specifies the playlist's YouTube * playlist ID. */ void set_id(const string& value) { _have_id_ = true; id_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * items that should be returned in the result set. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>mine</code>' attribute so it is no longer set. */ void clear_mine() { _have_mine_ = false; client::ClearCppValueHelper(&mine_); } /** * Gets the optional '<code>mine</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_mine() const { return mine_; } /** * Sets the '<code>mine</code>' attribute. * * @param[in] value Set this parameter's value to true to instruct the API * to only return playlists owned by the authenticated user. */ void set_mine(bool value) { _have_mine_ = true; mine_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken and prevPageToken properties identify other pages that * could be retrieved. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( PlaylistListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string channel_id_; string hl_; string id_; uint32 max_results_; bool mine_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; string page_token_; bool _have_channel_id_ : 1; bool _have_hl_ : 1; bool _have_id_ : 1; bool _have_max_results_ : 1; bool _have_mine_ : 1; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; bool _have_page_token_ : 1; DISALLOW_COPY_AND_ASSIGN(PlaylistsResource_ListMethod); }; typedef client::ServiceRequestPager< PlaylistsResource_ListMethod, PlaylistListResponse> PlaylistsResource_ListMethodPager; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class PlaylistsResource_UpdateMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * Note that this method will override the existing values for mutable * properties that are contained in any parts that the request body specifies. * For example, a playlist's description is contained in the snippet part, * which must be included in the request body. If the request does not specify * a value for the snippet.description property, the playlist's existing * description will be deleted. * @param[in] _content_ The data object to update. */ PlaylistsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Playlist& _content_); /** * Standard destructor. */ virtual ~PlaylistsResource_UpdateMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Playlist* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(PlaylistsResource_UpdateMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly * https://www.googleapis.com/auth/youtubepartner */ class SearchResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies a comma-separated list of one * or more search resource properties that the API response will include. Set * the parameter value to snippet. */ SearchResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~SearchResource_ListMethod(); /** * Clears the '<code>channelId</code>' attribute so it is no longer set. */ void clear_channel_id() { _have_channel_id_ = false; client::ClearCppValueHelper(&channel_id_); } /** * Gets the optional '<code>channelId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_channel_id() const { return channel_id_; } /** * Gets a modifiable pointer to the optional <code>channelId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_channelId() { _have_channel_id_ = true; return &channel_id_; } /** * Sets the '<code>channelId</code>' attribute. * * @param[in] value The channelId parameter indicates that the API response * should only contain resources created by the channel. */ void set_channel_id(const string& value) { _have_channel_id_ = true; channel_id_ = value; } /** * Clears the '<code>channelType</code>' attribute so it is no longer set. */ void clear_channel_type() { _have_channel_type_ = false; client::ClearCppValueHelper(&channel_type_); } /** * Gets the optional '<code>channelType</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_channel_type() const { return channel_type_; } /** * Gets a modifiable pointer to the optional <code>channelType</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_channelType() { _have_channel_type_ = true; return &channel_type_; } /** * Sets the '<code>channelType</code>' attribute. * * @param[in] value The channelType parameter lets you restrict a search to * a particular type of channel. */ void set_channel_type(const string& value) { _have_channel_type_ = true; channel_type_ = value; } /** * Clears the '<code>eventType</code>' attribute so it is no longer set. */ void clear_event_type() { _have_event_type_ = false; client::ClearCppValueHelper(&event_type_); } /** * Gets the optional '<code>eventType</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_event_type() const { return event_type_; } /** * Gets a modifiable pointer to the optional <code>eventType</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_eventType() { _have_event_type_ = true; return &event_type_; } /** * Sets the '<code>eventType</code>' attribute. * * @param[in] value The eventType parameter restricts a search to broadcast * events. If you specify a value for this parameter, you must also set the * type parameter's value to video. */ void set_event_type(const string& value) { _have_event_type_ = true; event_type_ = value; } /** * Clears the '<code>forContentOwner</code>' attribute so it is no longer * set. */ void clear_for_content_owner() { _have_for_content_owner_ = false; client::ClearCppValueHelper(&for_content_owner_); } /** * Gets the optional '<code>forContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_for_content_owner() const { return for_content_owner_; } /** * Sets the '<code>forContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The forContentOwner parameter restricts the search to only retrieve * resources owned by the content owner specified by the * onBehalfOfContentOwner parameter. The user must be authenticated using a * CMS account linked to the specified content owner and * onBehalfOfContentOwner must be provided. */ void set_for_content_owner(bool value) { _have_for_content_owner_ = true; for_content_owner_ = value; } /** * Clears the '<code>forDeveloper</code>' attribute so it is no longer set. */ void clear_for_developer() { _have_for_developer_ = false; client::ClearCppValueHelper(&for_developer_); } /** * Gets the optional '<code>forDeveloper</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_for_developer() const { return for_developer_; } /** * Sets the '<code>forDeveloper</code>' attribute. * * @param[in] value The forDeveloper parameter restricts the search to only * retrieve videos uploaded via the developer's application or website. The * API server uses the request's authorization credentials to identify the * developer. Therefore, a developer can restrict results to videos uploaded * through the developer's own app or website but not to videos uploaded * through other apps or sites. */ void set_for_developer(bool value) { _have_for_developer_ = true; for_developer_ = value; } /** * Clears the '<code>forMine</code>' attribute so it is no longer set. */ void clear_for_mine() { _have_for_mine_ = false; client::ClearCppValueHelper(&for_mine_); } /** * Gets the optional '<code>forMine</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_for_mine() const { return for_mine_; } /** * Sets the '<code>forMine</code>' attribute. * * @param[in] value The forMine parameter restricts the search to only * retrieve videos owned by the authenticated user. If you set this * parameter to true, then the type parameter's value must also be set to * video. */ void set_for_mine(bool value) { _have_for_mine_ = true; for_mine_ = value; } /** * Clears the '<code>location</code>' attribute so it is no longer set. */ void clear_location() { _have_location_ = false; client::ClearCppValueHelper(&location_); } /** * Gets the optional '<code>location</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_location() const { return location_; } /** * Gets a modifiable pointer to the optional <code>location</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_location() { _have_location_ = true; return &location_; } /** * Sets the '<code>location</code>' attribute. * * @param[in] value The location parameter, in conjunction with the * locationRadius parameter, defines a circular geographic area and also * restricts a search to videos that specify, in their metadata, a * geographic location that falls within that area. The parameter value is a * string that specifies latitude/longitude coordinates e.g. * (37.42307,-122.08427). * * * - The location parameter value identifies the point at the center of the * area. * - The locationRadius parameter specifies the maximum distance that the * location associated with a video can be from that point for the video to * still be included in the search results.The API returns an error if your * request specifies a value for the location parameter but does not also * specify a value for the locationRadius parameter. */ void set_location(const string& value) { _have_location_ = true; location_ = value; } /** * Clears the '<code>locationRadius</code>' attribute so it is no longer * set. */ void clear_location_radius() { _have_location_radius_ = false; client::ClearCppValueHelper(&location_radius_); } /** * Gets the optional '<code>locationRadius</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_location_radius() const { return location_radius_; } /** * Gets a modifiable pointer to the optional <code>locationRadius</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_locationRadius() { _have_location_radius_ = true; return &location_radius_; } /** * Sets the '<code>locationRadius</code>' attribute. * * @param[in] value The locationRadius parameter, in conjunction with the * location parameter, defines a circular geographic area. * * The parameter value must be a floating point number followed by a * measurement unit. Valid measurement units are m, km, ft, and mi. For * example, valid parameter values include 1500m, 5km, 10000ft, and 0.75mi. * The API does not support locationRadius parameter values larger than 1000 * kilometers. * * Note: See the definition of the location parameter for more information. */ void set_location_radius(const string& value) { _have_location_radius_ = true; location_radius_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * items that should be returned in the result set. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>order</code>' attribute so it is no longer set. */ void clear_order() { _have_order_ = false; client::ClearCppValueHelper(&order_); } /** * Gets the optional '<code>order</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_order() const { return order_; } /** * Gets a modifiable pointer to the optional <code>order</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_order() { _have_order_ = true; return &order_; } /** * Sets the '<code>order</code>' attribute. * * @param[in] value The order parameter specifies the method that will be * used to order resources in the API response. */ void set_order(const string& value) { _have_order_ = true; order_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken and prevPageToken properties identify other pages that * could be retrieved. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Clears the '<code>publishedAfter</code>' attribute so it is no longer * set. */ void clear_published_after() { _have_published_after_ = false; client::ClearCppValueHelper(&published_after_); } /** * Gets the optional '<code>publishedAfter</code>' attribute. * * If the value is not set then the default value will be returned. */ client::DateTime get_published_after() const { return published_after_; } /** * Sets the '<code>publishedAfter</code>' attribute. * * @param[in] value The publishedAfter parameter indicates that the API * response should only contain resources created after the specified time. * The value is an RFC 3339 formatted date-time value * (1970-01-01T00:00:00Z). */ void set_published_after(client::DateTime value) { _have_published_after_ = true; published_after_ = value; } /** * Clears the '<code>publishedBefore</code>' attribute so it is no longer * set. */ void clear_published_before() { _have_published_before_ = false; client::ClearCppValueHelper(&published_before_); } /** * Gets the optional '<code>publishedBefore</code>' attribute. * * If the value is not set then the default value will be returned. */ client::DateTime get_published_before() const { return published_before_; } /** * Sets the '<code>publishedBefore</code>' attribute. * * @param[in] value The publishedBefore parameter indicates that the API * response should only contain resources created before the specified time. * The value is an RFC 3339 formatted date-time value * (1970-01-01T00:00:00Z). */ void set_published_before(client::DateTime value) { _have_published_before_ = true; published_before_ = value; } /** * Clears the '<code>q</code>' attribute so it is no longer set. */ void clear_q() { _have_q_ = false; client::ClearCppValueHelper(&q_); } /** * Gets the optional '<code>q</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_q() const { return q_; } /** * Gets a modifiable pointer to the optional <code>q</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_q() { _have_q_ = true; return &q_; } /** * Sets the '<code>q</code>' attribute. * * @param[in] value The q parameter specifies the query term to search for. * * Your request can also use the Boolean NOT (-) and OR (|) operators to * exclude videos or to find videos that are associated with one of several * search terms. For example, to search for videos matching either "boating" * or "sailing", set the q parameter value to boating|sailing. Similarly, to * search for videos matching either "boating" or "sailing" but not * "fishing", set the q parameter value to boating|sailing -fishing. Note * that the pipe character must be URL-escaped when it is sent in your API * request. The URL-escaped value for the pipe character is %7C. */ void set_q(const string& value) { _have_q_ = true; q_ = value; } /** * Clears the '<code>regionCode</code>' attribute so it is no longer set. */ void clear_region_code() { _have_region_code_ = false; client::ClearCppValueHelper(&region_code_); } /** * Gets the optional '<code>regionCode</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_region_code() const { return region_code_; } /** * Gets a modifiable pointer to the optional <code>regionCode</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_regionCode() { _have_region_code_ = true; return &region_code_; } /** * Sets the '<code>regionCode</code>' attribute. * * @param[in] value The regionCode parameter instructs the API to return * search results for the specified country. The parameter value is an ISO * 3166-1 alpha-2 country code. */ void set_region_code(const string& value) { _have_region_code_ = true; region_code_ = value; } /** * Clears the '<code>relatedToVideoId</code>' attribute so it is no longer * set. */ void clear_related_to_video_id() { _have_related_to_video_id_ = false; client::ClearCppValueHelper(&related_to_video_id_); } /** * Gets the optional '<code>relatedToVideoId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_related_to_video_id() const { return related_to_video_id_; } /** * Gets a modifiable pointer to the optional <code>relatedToVideoId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_relatedToVideoId() { _have_related_to_video_id_ = true; return &related_to_video_id_; } /** * Sets the '<code>relatedToVideoId</code>' attribute. * * @param[in] value The relatedToVideoId parameter retrieves a list of * videos that are related to the video that the parameter value identifies. * The parameter value must be set to a YouTube video ID and, if you are * using this parameter, the type parameter must be set to video. */ void set_related_to_video_id(const string& value) { _have_related_to_video_id_ = true; related_to_video_id_ = value; } /** * Clears the '<code>relevanceLanguage</code>' attribute so it is no longer * set. */ void clear_relevance_language() { _have_relevance_language_ = false; client::ClearCppValueHelper(&relevance_language_); } /** * Gets the optional '<code>relevanceLanguage</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_relevance_language() const { return relevance_language_; } /** * Gets a modifiable pointer to the optional <code>relevanceLanguage</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_relevanceLanguage() { _have_relevance_language_ = true; return &relevance_language_; } /** * Sets the '<code>relevanceLanguage</code>' attribute. * * @param[in] value The relevanceLanguage parameter instructs the API to * return search results that are most relevant to the specified language. * The parameter value is typically an ISO 639-1 two-letter language code. * However, you should use the values zh-Hans for simplified Chinese and zh- * Hant for traditional Chinese. Please note that results in other languages * will still be returned if they are highly relevant to the search query * term. */ void set_relevance_language(const string& value) { _have_relevance_language_ = true; relevance_language_ = value; } /** * Clears the '<code>safeSearch</code>' attribute so it is no longer set. */ void clear_safe_search() { _have_safe_search_ = false; client::ClearCppValueHelper(&safe_search_); } /** * Gets the optional '<code>safeSearch</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_safe_search() const { return safe_search_; } /** * Gets a modifiable pointer to the optional <code>safeSearch</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_safeSearch() { _have_safe_search_ = true; return &safe_search_; } /** * Sets the '<code>safeSearch</code>' attribute. * * @param[in] value The safeSearch parameter indicates whether the search * results should include restricted content as well as standard content. */ void set_safe_search(const string& value) { _have_safe_search_ = true; safe_search_ = value; } /** * Clears the '<code>topicId</code>' attribute so it is no longer set. */ void clear_topic_id() { _have_topic_id_ = false; client::ClearCppValueHelper(&topic_id_); } /** * Gets the optional '<code>topicId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_topic_id() const { return topic_id_; } /** * Gets a modifiable pointer to the optional <code>topicId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_topicId() { _have_topic_id_ = true; return &topic_id_; } /** * Sets the '<code>topicId</code>' attribute. * * @param[in] value The topicId parameter indicates that the API response * should only contain resources associated with the specified topic. The * value identifies a Freebase topic ID. */ void set_topic_id(const string& value) { _have_topic_id_ = true; topic_id_ = value; } /** * Clears the '<code>type</code>' attribute so it is no longer set. */ void clear_type() { _have_type_ = false; client::ClearCppValueHelper(&type_); } /** * Gets the optional '<code>type</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_type() const { return type_; } /** * Gets a modifiable pointer to the optional <code>type</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_type() { _have_type_ = true; return &type_; } /** * Sets the '<code>type</code>' attribute. * * @param[in] value The type parameter restricts a search query to only * retrieve a particular type of resource. The value is a comma-separated * list of resource types. */ void set_type(const string& value) { _have_type_ = true; type_ = value; } /** * Clears the '<code>videoCaption</code>' attribute so it is no longer set. */ void clear_video_caption() { _have_video_caption_ = false; client::ClearCppValueHelper(&video_caption_); } /** * Gets the optional '<code>videoCaption</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_video_caption() const { return video_caption_; } /** * Gets a modifiable pointer to the optional <code>videoCaption</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_videoCaption() { _have_video_caption_ = true; return &video_caption_; } /** * Sets the '<code>videoCaption</code>' attribute. * * @param[in] value The videoCaption parameter indicates whether the API * should filter video search results based on whether they have captions. * If you specify a value for this parameter, you must also set the type * parameter's value to video. */ void set_video_caption(const string& value) { _have_video_caption_ = true; video_caption_ = value; } /** * Clears the '<code>videoCategoryId</code>' attribute so it is no longer * set. */ void clear_video_category_id() { _have_video_category_id_ = false; client::ClearCppValueHelper(&video_category_id_); } /** * Gets the optional '<code>videoCategoryId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_video_category_id() const { return video_category_id_; } /** * Gets a modifiable pointer to the optional <code>videoCategoryId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_videoCategoryId() { _have_video_category_id_ = true; return &video_category_id_; } /** * Sets the '<code>videoCategoryId</code>' attribute. * * @param[in] value The videoCategoryId parameter filters video search * results based on their category. If you specify a value for this * parameter, you must also set the type parameter's value to video. */ void set_video_category_id(const string& value) { _have_video_category_id_ = true; video_category_id_ = value; } /** * Clears the '<code>videoDefinition</code>' attribute so it is no longer * set. */ void clear_video_definition() { _have_video_definition_ = false; client::ClearCppValueHelper(&video_definition_); } /** * Gets the optional '<code>videoDefinition</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_video_definition() const { return video_definition_; } /** * Gets a modifiable pointer to the optional <code>videoDefinition</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_videoDefinition() { _have_video_definition_ = true; return &video_definition_; } /** * Sets the '<code>videoDefinition</code>' attribute. * * @param[in] value The videoDefinition parameter lets you restrict a search * to only include either high definition (HD) or standard definition (SD) * videos. HD videos are available for playback in at least 720p, though * higher resolutions, like 1080p, might also be available. If you specify a * value for this parameter, you must also set the type parameter's value to * video. */ void set_video_definition(const string& value) { _have_video_definition_ = true; video_definition_ = value; } /** * Clears the '<code>videoDimension</code>' attribute so it is no longer * set. */ void clear_video_dimension() { _have_video_dimension_ = false; client::ClearCppValueHelper(&video_dimension_); } /** * Gets the optional '<code>videoDimension</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_video_dimension() const { return video_dimension_; } /** * Gets a modifiable pointer to the optional <code>videoDimension</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_videoDimension() { _have_video_dimension_ = true; return &video_dimension_; } /** * Sets the '<code>videoDimension</code>' attribute. * * @param[in] value The videoDimension parameter lets you restrict a search * to only retrieve 2D or 3D videos. If you specify a value for this * parameter, you must also set the type parameter's value to video. */ void set_video_dimension(const string& value) { _have_video_dimension_ = true; video_dimension_ = value; } /** * Clears the '<code>videoDuration</code>' attribute so it is no longer set. */ void clear_video_duration() { _have_video_duration_ = false; client::ClearCppValueHelper(&video_duration_); } /** * Gets the optional '<code>videoDuration</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_video_duration() const { return video_duration_; } /** * Gets a modifiable pointer to the optional <code>videoDuration</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_videoDuration() { _have_video_duration_ = true; return &video_duration_; } /** * Sets the '<code>videoDuration</code>' attribute. * * @param[in] value The videoDuration parameter filters video search results * based on their duration. If you specify a value for this parameter, you * must also set the type parameter's value to video. */ void set_video_duration(const string& value) { _have_video_duration_ = true; video_duration_ = value; } /** * Clears the '<code>videoEmbeddable</code>' attribute so it is no longer * set. */ void clear_video_embeddable() { _have_video_embeddable_ = false; client::ClearCppValueHelper(&video_embeddable_); } /** * Gets the optional '<code>videoEmbeddable</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_video_embeddable() const { return video_embeddable_; } /** * Gets a modifiable pointer to the optional <code>videoEmbeddable</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_videoEmbeddable() { _have_video_embeddable_ = true; return &video_embeddable_; } /** * Sets the '<code>videoEmbeddable</code>' attribute. * * @param[in] value The videoEmbeddable parameter lets you to restrict a * search to only videos that can be embedded into a webpage. If you specify * a value for this parameter, you must also set the type parameter's value * to video. */ void set_video_embeddable(const string& value) { _have_video_embeddable_ = true; video_embeddable_ = value; } /** * Clears the '<code>videoLicense</code>' attribute so it is no longer set. */ void clear_video_license() { _have_video_license_ = false; client::ClearCppValueHelper(&video_license_); } /** * Gets the optional '<code>videoLicense</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_video_license() const { return video_license_; } /** * Gets a modifiable pointer to the optional <code>videoLicense</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_videoLicense() { _have_video_license_ = true; return &video_license_; } /** * Sets the '<code>videoLicense</code>' attribute. * * @param[in] value The videoLicense parameter filters search results to * only include videos with a particular license. YouTube lets video * uploaders choose to attach either the Creative Commons license or the * standard YouTube license to each of their videos. If you specify a value * for this parameter, you must also set the type parameter's value to * video. */ void set_video_license(const string& value) { _have_video_license_ = true; video_license_ = value; } /** * Clears the '<code>videoSyndicated</code>' attribute so it is no longer * set. */ void clear_video_syndicated() { _have_video_syndicated_ = false; client::ClearCppValueHelper(&video_syndicated_); } /** * Gets the optional '<code>videoSyndicated</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_video_syndicated() const { return video_syndicated_; } /** * Gets a modifiable pointer to the optional <code>videoSyndicated</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_videoSyndicated() { _have_video_syndicated_ = true; return &video_syndicated_; } /** * Sets the '<code>videoSyndicated</code>' attribute. * * @param[in] value The videoSyndicated parameter lets you to restrict a * search to only videos that can be played outside youtube.com. If you * specify a value for this parameter, you must also set the type * parameter's value to video. */ void set_video_syndicated(const string& value) { _have_video_syndicated_ = true; video_syndicated_ = value; } /** * Clears the '<code>videoType</code>' attribute so it is no longer set. */ void clear_video_type() { _have_video_type_ = false; client::ClearCppValueHelper(&video_type_); } /** * Gets the optional '<code>videoType</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_video_type() const { return video_type_; } /** * Gets a modifiable pointer to the optional <code>videoType</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_videoType() { _have_video_type_ = true; return &video_type_; } /** * Sets the '<code>videoType</code>' attribute. * * @param[in] value The videoType parameter lets you restrict a search to a * particular type of videos. If you specify a value for this parameter, you * must also set the type parameter's value to video. */ void set_video_type(const string& value) { _have_video_type_ = true; video_type_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( SearchListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string channel_id_; string channel_type_; string event_type_; bool for_content_owner_; bool for_developer_; bool for_mine_; string location_; string location_radius_; uint32 max_results_; string on_behalf_of_content_owner_; string order_; string page_token_; client::DateTime published_after_; client::DateTime published_before_; string q_; string region_code_; string related_to_video_id_; string relevance_language_; string safe_search_; string topic_id_; string type_; string video_caption_; string video_category_id_; string video_definition_; string video_dimension_; string video_duration_; string video_embeddable_; string video_license_; string video_syndicated_; string video_type_; bool _have_channel_id_ : 1; bool _have_channel_type_ : 1; bool _have_event_type_ : 1; bool _have_for_content_owner_ : 1; bool _have_for_developer_ : 1; bool _have_for_mine_ : 1; bool _have_location_ : 1; bool _have_location_radius_ : 1; bool _have_max_results_ : 1; bool _have_on_behalf_of_content_owner_ : 1; bool _have_order_ : 1; bool _have_page_token_ : 1; bool _have_published_after_ : 1; bool _have_published_before_ : 1; bool _have_q_ : 1; bool _have_region_code_ : 1; bool _have_related_to_video_id_ : 1; bool _have_relevance_language_ : 1; bool _have_safe_search_ : 1; bool _have_topic_id_ : 1; bool _have_type_ : 1; bool _have_video_caption_ : 1; bool _have_video_category_id_ : 1; bool _have_video_definition_ : 1; bool _have_video_dimension_ : 1; bool _have_video_duration_ : 1; bool _have_video_embeddable_ : 1; bool _have_video_license_ : 1; bool _have_video_syndicated_ : 1; bool _have_video_type_ : 1; DISALLOW_COPY_AND_ASSIGN(SearchResource_ListMethod); }; typedef client::ServiceRequestPager< SearchResource_ListMethod, SearchListResponse> SearchResource_ListMethodPager; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly */ class SponsorsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies the sponsor resource parts * that the API response will include. Supported values are id and snippet. */ SponsorsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~SponsorsResource_ListMethod(); /** * Clears the '<code>filter</code>' attribute so it is no longer set. */ void clear_filter() { _have_filter_ = false; client::ClearCppValueHelper(&filter_); } /** * Gets the optional '<code>filter</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_filter() const { return filter_; } /** * Gets a modifiable pointer to the optional <code>filter</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_filter() { _have_filter_ = true; return &filter_; } /** * Sets the '<code>filter</code>' attribute. * * @param[in] value The filter parameter specifies which channel sponsors to * return. */ void set_filter(const string& value) { _have_filter_ = true; filter_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * items that should be returned in the result set. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken and prevPageToken properties identify other pages that * could be retrieved. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( SponsorListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string filter_; uint32 max_results_; string page_token_; bool _have_filter_ : 1; bool _have_max_results_ : 1; bool _have_page_token_ : 1; DISALLOW_COPY_AND_ASSIGN(SponsorsResource_ListMethod); }; typedef client::ServiceRequestPager< SponsorsResource_ListMethod, SponsorListResponse> SponsorsResource_ListMethodPager; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class SubscriptionsResource_DeleteMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter specifies the YouTube subscription ID for * the resource that is being deleted. In a subscription resource, the id * property specifies the YouTube subscription ID. */ SubscriptionsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id); /** * Standard destructor. */ virtual ~SubscriptionsResource_DeleteMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string id_; DISALLOW_COPY_AND_ASSIGN(SubscriptionsResource_DeleteMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class SubscriptionsResource_InsertMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * @param[in] _content_ The data object to insert. */ SubscriptionsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Subscription& _content_); /** * Standard destructor. */ virtual ~SubscriptionsResource_InsertMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Subscription* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string _content_; DISALLOW_COPY_AND_ASSIGN(SubscriptionsResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly * https://www.googleapis.com/auth/youtubepartner */ class SubscriptionsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies a comma-separated list of one * or more subscription resource properties that the API response will * include. * * If the parameter identifies a property that contains child properties, the * child properties will be included in the response. For example, in a * subscription resource, the snippet property contains other properties, such * as a display title for the subscription. If you set part=snippet, the API * response will also contain all of those nested properties. */ SubscriptionsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~SubscriptionsResource_ListMethod(); /** * Clears the '<code>channelId</code>' attribute so it is no longer set. */ void clear_channel_id() { _have_channel_id_ = false; client::ClearCppValueHelper(&channel_id_); } /** * Gets the optional '<code>channelId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_channel_id() const { return channel_id_; } /** * Gets a modifiable pointer to the optional <code>channelId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_channelId() { _have_channel_id_ = true; return &channel_id_; } /** * Sets the '<code>channelId</code>' attribute. * * @param[in] value The channelId parameter specifies a YouTube channel ID. * The API will only return that channel's subscriptions. */ void set_channel_id(const string& value) { _have_channel_id_ = true; channel_id_ = value; } /** * Clears the '<code>forChannelId</code>' attribute so it is no longer set. */ void clear_for_channel_id() { _have_for_channel_id_ = false; client::ClearCppValueHelper(&for_channel_id_); } /** * Gets the optional '<code>forChannelId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_for_channel_id() const { return for_channel_id_; } /** * Gets a modifiable pointer to the optional <code>forChannelId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_forChannelId() { _have_for_channel_id_ = true; return &for_channel_id_; } /** * Sets the '<code>forChannelId</code>' attribute. * * @param[in] value The forChannelId parameter specifies a comma-separated * list of channel IDs. The API response will then only contain * subscriptions matching those channels. */ void set_for_channel_id(const string& value) { _have_for_channel_id_ = true; for_channel_id_ = value; } /** * Clears the '<code>id</code>' attribute so it is no longer set. */ void clear_id() { _have_id_ = false; client::ClearCppValueHelper(&id_); } /** * Gets the optional '<code>id</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_id() const { return id_; } /** * Gets a modifiable pointer to the optional <code>id</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_id() { _have_id_ = true; return &id_; } /** * Sets the '<code>id</code>' attribute. * * @param[in] value The id parameter specifies a comma-separated list of the * YouTube subscription ID(s) for the resource(s) that are being retrieved. * In a subscription resource, the id property specifies the YouTube * subscription ID. */ void set_id(const string& value) { _have_id_ = true; id_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * items that should be returned in the result set. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>mine</code>' attribute so it is no longer set. */ void clear_mine() { _have_mine_ = false; client::ClearCppValueHelper(&mine_); } /** * Gets the optional '<code>mine</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_mine() const { return mine_; } /** * Sets the '<code>mine</code>' attribute. * * @param[in] value Set this parameter's value to true to retrieve a feed of * the authenticated user's subscriptions. */ void set_mine(bool value) { _have_mine_ = true; mine_ = value; } /** * Clears the '<code>myRecentSubscribers</code>' attribute so it is no * longer set. */ void clear_my_recent_subscribers() { _have_my_recent_subscribers_ = false; client::ClearCppValueHelper(&my_recent_subscribers_); } /** * Gets the optional '<code>myRecentSubscribers</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_my_recent_subscribers() const { return my_recent_subscribers_; } /** * Sets the '<code>myRecentSubscribers</code>' attribute. * * @param[in] value Set this parameter's value to true to retrieve a feed of * the subscribers of the authenticated user in reverse chronological order * (newest first). */ void set_my_recent_subscribers(bool value) { _have_my_recent_subscribers_ = true; my_recent_subscribers_ = value; } /** * Clears the '<code>mySubscribers</code>' attribute so it is no longer set. */ void clear_my_subscribers() { _have_my_subscribers_ = false; client::ClearCppValueHelper(&my_subscribers_); } /** * Gets the optional '<code>mySubscribers</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_my_subscribers() const { return my_subscribers_; } /** * Sets the '<code>mySubscribers</code>' attribute. * * @param[in] value Set this parameter's value to true to retrieve a feed of * the subscribers of the authenticated user in no particular order. */ void set_my_subscribers(bool value) { _have_my_subscribers_ = true; my_subscribers_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Clears the '<code>order</code>' attribute so it is no longer set. */ void clear_order() { _have_order_ = false; client::ClearCppValueHelper(&order_); } /** * Gets the optional '<code>order</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_order() const { return order_; } /** * Gets a modifiable pointer to the optional <code>order</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_order() { _have_order_ = true; return &order_; } /** * Sets the '<code>order</code>' attribute. * * @param[in] value The order parameter specifies the method that will be * used to sort resources in the API response. */ void set_order(const string& value) { _have_order_ = true; order_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken and prevPageToken properties identify other pages that * could be retrieved. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( SubscriptionListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string channel_id_; string for_channel_id_; string id_; uint32 max_results_; bool mine_; bool my_recent_subscribers_; bool my_subscribers_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; string order_; string page_token_; bool _have_channel_id_ : 1; bool _have_for_channel_id_ : 1; bool _have_id_ : 1; bool _have_max_results_ : 1; bool _have_mine_ : 1; bool _have_my_recent_subscribers_ : 1; bool _have_my_subscribers_ : 1; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; bool _have_order_ : 1; bool _have_page_token_ : 1; DISALLOW_COPY_AND_ASSIGN(SubscriptionsResource_ListMethod); }; typedef client::ServiceRequestPager< SubscriptionsResource_ListMethod, SubscriptionListResponse> SubscriptionsResource_ListMethodPager; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly */ class SuperChatEventsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies the superChatEvent resource * parts that the API response will include. Supported values are id and * snippet. */ SuperChatEventsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~SuperChatEventsResource_ListMethod(); /** * Clears the '<code>hl</code>' attribute so it is no longer set. */ void clear_hl() { _have_hl_ = false; client::ClearCppValueHelper(&hl_); } /** * Gets the optional '<code>hl</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_hl() const { return hl_; } /** * Gets a modifiable pointer to the optional <code>hl</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_hl() { _have_hl_ = true; return &hl_; } /** * Sets the '<code>hl</code>' attribute. * * @param[in] value The hl parameter instructs the API to retrieve localized * resource metadata for a specific application language that the YouTube * website supports. The parameter value must be a language code included in * the list returned by the i18nLanguages.list method. * * If localized resource details are available in that language, the * resource's snippet.localized object will contain the localized values. * However, if localized details are not available, the snippet.localized * object will contain resource details in the resource's default language. */ void set_hl(const string& value) { _have_hl_ = true; hl_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * items that should be returned in the result set. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken and prevPageToken properties identify other pages that * could be retrieved. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( SuperChatEventListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string hl_; uint32 max_results_; string page_token_; bool _have_hl_ : 1; bool _have_max_results_ : 1; bool _have_page_token_ : 1; DISALLOW_COPY_AND_ASSIGN(SuperChatEventsResource_ListMethod); }; typedef client::ServiceRequestPager< SuperChatEventsResource_ListMethod, SuperChatEventListResponse> SuperChatEventsResource_ListMethodPager; /** * Implements the set method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.upload * https://www.googleapis.com/auth/youtubepartner */ class ThumbnailsResource_SetMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] video_id The videoId parameter specifies a YouTube video ID for * which the custom video thumbnail is being provided. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to set. If * this is NULL then do not upload any media and ignore * _media_content_type_. */ ThumbnailsResource_SetMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& video_id, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_); /** * Standard destructor. */ virtual ~ThumbnailsResource_SetMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * actual CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( ThumbnailSetResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } /** * Returns MediaUploader for uploading the content. */ /** * Returns the specification for media upload using the simple protocol. */ static const client::MediaUploadSpec SIMPLE_MEDIA_UPLOAD; /** * Returns the specification for media upload using the resumable protocol. */ static const client::MediaUploadSpec RESUMABLE_MEDIA_UPLOAD; private: string video_id_; string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; DISALLOW_COPY_AND_ASSIGN(ThumbnailsResource_SetMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly */ class VideoAbuseReportReasonsResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies the videoCategory resource * parts that the API response will include. Supported values are id and * snippet. */ VideoAbuseReportReasonsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~VideoAbuseReportReasonsResource_ListMethod(); /** * Clears the '<code>hl</code>' attribute so it is no longer set. */ void clear_hl() { _have_hl_ = false; client::ClearCppValueHelper(&hl_); } /** * Gets the optional '<code>hl</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_hl() const { return hl_; } /** * Gets a modifiable pointer to the optional <code>hl</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_hl() { _have_hl_ = true; return &hl_; } /** * Sets the '<code>hl</code>' attribute. * * @param[in] value The hl parameter specifies the language that should be * used for text values in the API response. */ void set_hl(const string& value) { _have_hl_ = true; hl_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( VideoAbuseReportReasonListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string hl_; bool _have_hl_ : 1; DISALLOW_COPY_AND_ASSIGN(VideoAbuseReportReasonsResource_ListMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly * https://www.googleapis.com/auth/youtubepartner */ class VideoCategoriesResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies the videoCategory resource * properties that the API response will include. Set the parameter value to * snippet. */ VideoCategoriesResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~VideoCategoriesResource_ListMethod(); /** * Clears the '<code>hl</code>' attribute so it is no longer set. */ void clear_hl() { _have_hl_ = false; client::ClearCppValueHelper(&hl_); } /** * Gets the optional '<code>hl</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_hl() const { return hl_; } /** * Gets a modifiable pointer to the optional <code>hl</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_hl() { _have_hl_ = true; return &hl_; } /** * Sets the '<code>hl</code>' attribute. * * @param[in] value The hl parameter specifies the language that should be * used for text values in the API response. */ void set_hl(const string& value) { _have_hl_ = true; hl_ = value; } /** * Clears the '<code>id</code>' attribute so it is no longer set. */ void clear_id() { _have_id_ = false; client::ClearCppValueHelper(&id_); } /** * Gets the optional '<code>id</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_id() const { return id_; } /** * Gets a modifiable pointer to the optional <code>id</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_id() { _have_id_ = true; return &id_; } /** * Sets the '<code>id</code>' attribute. * * @param[in] value The id parameter specifies a comma-separated list of * video category IDs for the resources that you are retrieving. */ void set_id(const string& value) { _have_id_ = true; id_ = value; } /** * Clears the '<code>regionCode</code>' attribute so it is no longer set. */ void clear_region_code() { _have_region_code_ = false; client::ClearCppValueHelper(&region_code_); } /** * Gets the optional '<code>regionCode</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_region_code() const { return region_code_; } /** * Gets a modifiable pointer to the optional <code>regionCode</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_regionCode() { _have_region_code_ = true; return &region_code_; } /** * Sets the '<code>regionCode</code>' attribute. * * @param[in] value The regionCode parameter instructs the API to return the * list of video categories available in the specified country. The * parameter value is an ISO 3166-1 alpha-2 country code. */ void set_region_code(const string& value) { _have_region_code_ = true; region_code_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( VideoCategoryListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string hl_; string id_; string region_code_; bool _have_hl_ : 1; bool _have_id_ : 1; bool _have_region_code_ : 1; DISALLOW_COPY_AND_ASSIGN(VideoCategoriesResource_ListMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class VideosResource_DeleteMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter specifies the YouTube video ID for the * resource that is being deleted. In a video resource, the id property * specifies the video's ID. */ VideosResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id); /** * Standard destructor. */ virtual ~VideosResource_DeleteMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * actual CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string id_; string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; DISALLOW_COPY_AND_ASSIGN(VideosResource_DeleteMethod); }; /** * Implements the getRating method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class VideosResource_GetRatingMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter specifies a comma-separated list of the * YouTube video ID(s) for the resource(s) for which you are retrieving rating * data. In a video resource, the id property specifies the video's ID. */ VideosResource_GetRatingMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id); /** * Standard destructor. */ virtual ~VideosResource_GetRatingMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( VideoGetRatingResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string id_; string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; DISALLOW_COPY_AND_ASSIGN(VideosResource_GetRatingMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.upload * https://www.googleapis.com/auth/youtubepartner */ class VideosResource_InsertMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * * @deprecated in favor constructor that includes the media upload parameters. * * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * Note that not all parts contain properties that can be set when inserting * or updating a video. For example, the statistics object encapsulates * statistics that YouTube calculates for a video and does not contain values * that you can set or modify. If the parameter value specifies a part that * does not contain mutable values, that part will still be included in the * API response. * * @param[in] _content_ The data object to insert. */ VideosResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * Note that not all parts contain properties that can be set when inserting * or updating a video. For example, the statistics object encapsulates * statistics that YouTube calculates for a video and does not contain values * that you can set or modify. If the parameter value specifies a part that * does not contain mutable values, that part will still be included in the * API response. * @param[in] _metadata_ The metadata object to insert. If this * is NULL then do not upload any metadata. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to insert. If * this is NULL then do not upload any media and ignore * _media_content_type_. */ VideosResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Video* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_); /** * Standard destructor. */ virtual ~VideosResource_InsertMethod(); /** * Clears the '<code>autoLevels</code>' attribute so it is no longer set. */ void clear_auto_levels() { _have_auto_levels_ = false; client::ClearCppValueHelper(&auto_levels_); } /** * Gets the optional '<code>autoLevels</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_auto_levels() const { return auto_levels_; } /** * Sets the '<code>autoLevels</code>' attribute. * * @param[in] value The autoLevels parameter indicates whether YouTube * should automatically enhance the video's lighting and color. */ void set_auto_levels(bool value) { _have_auto_levels_ = true; auto_levels_ = value; } /** * Clears the '<code>notifySubscribers</code>' attribute so it is no longer * set. */ void clear_notify_subscribers() { _have_notify_subscribers_ = false; client::ClearCppValueHelper(&notify_subscribers_); } /** * Gets the optional '<code>notifySubscribers</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_notify_subscribers() const { return notify_subscribers_; } /** * Sets the '<code>notifySubscribers</code>' attribute. * * @param[in] value The notifySubscribers parameter indicates whether * YouTube should send a notification about the new video to users who * subscribe to the video's channel. A parameter value of True indicates * that subscribers will be notified of newly uploaded videos. However, a * channel owner who is uploading many videos might prefer to set the value * to False to avoid sending a notification about each new video to the * channel's subscribers. */ void set_notify_subscribers(bool value) { _have_notify_subscribers_ = true; notify_subscribers_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>onBehalfOfContentOwnerChannel</code>' attribute so it * is no longer set. */ void clear_on_behalf_of_content_owner_channel() { _have_on_behalf_of_content_owner_channel_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_channel_); } /** * Gets the optional '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner_channel() const { return on_behalf_of_content_owner_channel_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwnerChannel</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwnerChannel() { _have_on_behalf_of_content_owner_channel_ = true; return &on_behalf_of_content_owner_channel_; } /** * Sets the '<code>onBehalfOfContentOwnerChannel</code>' attribute. * * @param[in] value This parameter can only be used in a properly authorized * request. Note: This parameter is intended exclusively for YouTube content * partners. * * The onBehalfOfContentOwnerChannel parameter specifies the YouTube channel * ID of the channel to which a video is being added. This parameter is * required when a request specifies a value for the onBehalfOfContentOwner * parameter, and it can only be used in conjunction with that parameter. In * addition, the request must be authorized using a CMS account that is * linked to the content owner that the onBehalfOfContentOwner parameter * specifies. Finally, the channel that the onBehalfOfContentOwnerChannel * parameter value specifies must be linked to the content owner that the * onBehalfOfContentOwner parameter specifies. * * This parameter is intended for YouTube content partners that own and * manage many different YouTube channels. It allows content owners to * authenticate once and perform actions on behalf of the channel specified * in the parameter value, without having to provide authentication * credentials for each separate channel. */ void set_on_behalf_of_content_owner_channel(const string& value) { _have_on_behalf_of_content_owner_channel_ = true; on_behalf_of_content_owner_channel_ = value; } /** * Clears the '<code>stabilize</code>' attribute so it is no longer set. */ void clear_stabilize() { _have_stabilize_ = false; client::ClearCppValueHelper(&stabilize_); } /** * Gets the optional '<code>stabilize</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_stabilize() const { return stabilize_; } /** * Sets the '<code>stabilize</code>' attribute. * * @param[in] value The stabilize parameter indicates whether YouTube should * adjust the video to remove shaky camera motions. */ void set_stabilize(bool value) { _have_stabilize_ = true; stabilize_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Video* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } /** * Returns MediaUploader for uploading the content. */ /** * Returns the specification for media upload using the simple protocol. */ static const client::MediaUploadSpec SIMPLE_MEDIA_UPLOAD; /** * Returns the specification for media upload using the resumable protocol. */ static const client::MediaUploadSpec RESUMABLE_MEDIA_UPLOAD; private: string part_; bool auto_levels_; bool notify_subscribers_; string on_behalf_of_content_owner_; string on_behalf_of_content_owner_channel_; bool stabilize_; bool _have_auto_levels_ : 1; bool _have_notify_subscribers_ : 1; bool _have_on_behalf_of_content_owner_ : 1; bool _have_on_behalf_of_content_owner_channel_ : 1; bool _have_stabilize_ : 1; DISALLOW_COPY_AND_ASSIGN(VideosResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.readonly * https://www.googleapis.com/auth/youtubepartner */ class VideosResource_ListMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter specifies a comma-separated list of one * or more video resource properties that the API response will include. * * If the parameter identifies a property that contains child properties, the * child properties will be included in the response. For example, in a video * resource, the snippet property contains the channelId, title, description, * tags, and categoryId properties. As such, if you set part=snippet, the API * response will contain all of those properties. */ VideosResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part); /** * Standard destructor. */ virtual ~VideosResource_ListMethod(); /** * Clears the '<code>chart</code>' attribute so it is no longer set. */ void clear_chart() { _have_chart_ = false; client::ClearCppValueHelper(&chart_); } /** * Gets the optional '<code>chart</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_chart() const { return chart_; } /** * Gets a modifiable pointer to the optional <code>chart</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_chart() { _have_chart_ = true; return &chart_; } /** * Sets the '<code>chart</code>' attribute. * * @param[in] value The chart parameter identifies the chart that you want * to retrieve. */ void set_chart(const string& value) { _have_chart_ = true; chart_ = value; } /** * Clears the '<code>hl</code>' attribute so it is no longer set. */ void clear_hl() { _have_hl_ = false; client::ClearCppValueHelper(&hl_); } /** * Gets the optional '<code>hl</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_hl() const { return hl_; } /** * Gets a modifiable pointer to the optional <code>hl</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_hl() { _have_hl_ = true; return &hl_; } /** * Sets the '<code>hl</code>' attribute. * * @param[in] value The hl parameter instructs the API to retrieve localized * resource metadata for a specific application language that the YouTube * website supports. The parameter value must be a language code included in * the list returned by the i18nLanguages.list method. * * If localized resource details are available in that language, the * resource's snippet.localized object will contain the localized values. * However, if localized details are not available, the snippet.localized * object will contain resource details in the resource's default language. */ void set_hl(const string& value) { _have_hl_ = true; hl_ = value; } /** * Clears the '<code>id</code>' attribute so it is no longer set. */ void clear_id() { _have_id_ = false; client::ClearCppValueHelper(&id_); } /** * Gets the optional '<code>id</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_id() const { return id_; } /** * Gets a modifiable pointer to the optional <code>id</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_id() { _have_id_ = true; return &id_; } /** * Sets the '<code>id</code>' attribute. * * @param[in] value The id parameter specifies a comma-separated list of the * YouTube video ID(s) for the resource(s) that are being retrieved. In a * video resource, the id property specifies the video's ID. */ void set_id(const string& value) { _have_id_ = true; id_ = value; } /** * Clears the '<code>locale</code>' attribute so it is no longer set. */ void clear_locale() { _have_locale_ = false; client::ClearCppValueHelper(&locale_); } /** * Gets the optional '<code>locale</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_locale() const { return locale_; } /** * Gets a modifiable pointer to the optional <code>locale</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_locale() { _have_locale_ = true; return &locale_; } /** * Sets the '<code>locale</code>' attribute. * @deprecated * * @param[in] value DEPRECATED. */ void set_locale(const string& value) { _have_locale_ = true; locale_ = value; } /** * Clears the '<code>maxHeight</code>' attribute so it is no longer set. */ void clear_max_height() { _have_max_height_ = false; client::ClearCppValueHelper(&max_height_); } /** * Gets the optional '<code>maxHeight</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_height() const { return max_height_; } /** * Sets the '<code>maxHeight</code>' attribute. * * @param[in] value The maxHeight parameter specifies a maximum height of * the embedded player. If maxWidth is provided, maxHeight may not be * reached in order to not violate the width request. */ void set_max_height(uint32 value) { _have_max_height_ = true; max_height_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maxResults parameter specifies the maximum number of * items that should be returned in the result set. * * Note: This parameter is supported for use in conjunction with the * myRating and chart parameters, but it is not supported for use in * conjunction with the id parameter. */ void set_max_results(uint32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>maxWidth</code>' attribute so it is no longer set. */ void clear_max_width() { _have_max_width_ = false; client::ClearCppValueHelper(&max_width_); } /** * Gets the optional '<code>maxWidth</code>' attribute. * * If the value is not set then the default value will be returned. */ uint32 get_max_width() const { return max_width_; } /** * Sets the '<code>maxWidth</code>' attribute. * * @param[in] value The maxWidth parameter specifies a maximum width of the * embedded player. If maxHeight is provided, maxWidth may not be reached in * order to not violate the height request. */ void set_max_width(uint32 value) { _have_max_width_ = true; max_width_ = value; } /** * Clears the '<code>myRating</code>' attribute so it is no longer set. */ void clear_my_rating() { _have_my_rating_ = false; client::ClearCppValueHelper(&my_rating_); } /** * Gets the optional '<code>myRating</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_my_rating() const { return my_rating_; } /** * Gets a modifiable pointer to the optional <code>myRating</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_myRating() { _have_my_rating_ = true; return &my_rating_; } /** * Sets the '<code>myRating</code>' attribute. * * @param[in] value Set this parameter's value to like or dislike to * instruct the API to only return videos liked or disliked by the * authenticated user. */ void set_my_rating(const string& value) { _have_my_rating_ = true; my_rating_ = value; } /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The pageToken parameter identifies a specific page in * the result set that should be returned. In an API response, the * nextPageToken and prevPageToken properties identify other pages that * could be retrieved. * * Note: This parameter is supported for use in conjunction with the * myRating and chart parameters, but it is not supported for use in * conjunction with the id parameter. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Clears the '<code>regionCode</code>' attribute so it is no longer set. */ void clear_region_code() { _have_region_code_ = false; client::ClearCppValueHelper(&region_code_); } /** * Gets the optional '<code>regionCode</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_region_code() const { return region_code_; } /** * Gets a modifiable pointer to the optional <code>regionCode</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_regionCode() { _have_region_code_ = true; return &region_code_; } /** * Sets the '<code>regionCode</code>' attribute. * * @param[in] value The regionCode parameter instructs the API to select a * video chart available in the specified region. This parameter can only be * used in conjunction with the chart parameter. The parameter value is an * ISO 3166-1 alpha-2 country code. */ void set_region_code(const string& value) { _have_region_code_ = true; region_code_ = value; } /** * Clears the '<code>videoCategoryId</code>' attribute so it is no longer * set. */ void clear_video_category_id() { _have_video_category_id_ = false; client::ClearCppValueHelper(&video_category_id_); } /** * Gets the optional '<code>videoCategoryId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_video_category_id() const { return video_category_id_; } /** * Gets a modifiable pointer to the optional <code>videoCategoryId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_videoCategoryId() { _have_video_category_id_ = true; return &video_category_id_; } /** * Sets the '<code>videoCategoryId</code>' attribute. * * @param[in] value The videoCategoryId parameter identifies the video * category for which the chart should be retrieved. This parameter can only * be used in conjunction with the chart parameter. By default, charts are * not restricted to a particular category. */ void set_video_category_id(const string& value) { _have_video_category_id_ = true; video_category_id_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( VideoListResponse* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string chart_; string hl_; string id_; string locale_; uint32 max_height_; uint32 max_results_; uint32 max_width_; string my_rating_; string on_behalf_of_content_owner_; string page_token_; string region_code_; string video_category_id_; bool _have_chart_ : 1; bool _have_hl_ : 1; bool _have_id_ : 1; bool _have_locale_ : 1; bool _have_max_height_ : 1; bool _have_max_results_ : 1; bool _have_max_width_ : 1; bool _have_my_rating_ : 1; bool _have_on_behalf_of_content_owner_ : 1; bool _have_page_token_ : 1; bool _have_region_code_ : 1; bool _have_video_category_id_ : 1; DISALLOW_COPY_AND_ASSIGN(VideosResource_ListMethod); }; typedef client::ServiceRequestPager< VideosResource_ListMethod, VideoListResponse> VideosResource_ListMethodPager; /** * Implements the rate method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class VideosResource_RateMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] id The id parameter specifies the YouTube video ID of the video * that is being rated or having its rating removed. * @param[in] rating Specifies the rating to record. */ VideosResource_RateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& rating); /** * Standard destructor. */ virtual ~VideosResource_RateMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string id_; string rating_; DISALLOW_COPY_AND_ASSIGN(VideosResource_RateMethod); }; /** * Implements the reportAbuse method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class VideosResource_ReportAbuseMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] _content_ The data object to reportAbuse. */ VideosResource_ReportAbuseMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const VideoAbuseReport& _content_); /** * Standard destructor. */ virtual ~VideosResource_ReportAbuseMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(VideosResource_ReportAbuseMethod); }; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class VideosResource_UpdateMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * Note that this method will override the existing values for all of the * mutable properties that are contained in any parts that the parameter value * specifies. For example, a video's privacy setting is contained in the * status part. As such, if your request is updating a private video, and the * request's part parameter value includes the status part, the video's * privacy setting will be updated to whatever value the request body * specifies. If the request body does not specify a value, the existing * privacy setting will be removed and the video will revert to the default * privacy setting. * * In addition, not all parts contain properties that can be set when * inserting or updating a video. For example, the statistics object * encapsulates statistics that YouTube calculates for a video and does not * contain values that you can set or modify. If the parameter value specifies * a part that does not contain mutable values, that part will still be * included in the API response. * @param[in] _content_ The data object to update. */ VideosResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Video& _content_); /** * Standard destructor. */ virtual ~VideosResource_UpdateMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * actual CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Video* data) { return YouTubeServiceBaseRequest::ExecuteAndParseResponse(data); } private: string part_; string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(VideosResource_UpdateMethod); }; /** * Implements the set method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtube.upload * https://www.googleapis.com/auth/youtubepartner */ class WatermarksResource_SetMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * * @deprecated in favor constructor that includes the media upload parameters. * * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] channel_id The channelId parameter specifies the YouTube channel * ID for which the watermark is being provided. * * @param[in] _content_ The data object to set. */ WatermarksResource_SetMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& channel_id); /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] channel_id The channelId parameter specifies the YouTube channel * ID for which the watermark is being provided. * @param[in] _metadata_ The metadata object to set. If this * is NULL then do not upload any metadata. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to set. If * this is NULL then do not upload any media and ignore * _media_content_type_. */ WatermarksResource_SetMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& channel_id, const InvideoBranding* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_); /** * Standard destructor. */ virtual ~WatermarksResource_SetMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Returns MediaUploader for uploading the content. */ /** * Returns the specification for media upload using the simple protocol. */ static const client::MediaUploadSpec SIMPLE_MEDIA_UPLOAD; /** * Returns the specification for media upload using the resumable protocol. */ static const client::MediaUploadSpec RESUMABLE_MEDIA_UPLOAD; private: string channel_id_; string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; DISALLOW_COPY_AND_ASSIGN(WatermarksResource_SetMethod); }; /** * Implements the unset method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/youtube * https://www.googleapis.com/auth/youtube.force-ssl * https://www.googleapis.com/auth/youtubepartner */ class WatermarksResource_UnsetMethod : public YouTubeServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] channel_id The channelId parameter specifies the YouTube channel * ID for which the watermark is being unset. */ WatermarksResource_UnsetMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& channel_id); /** * Standard destructor. */ virtual ~WatermarksResource_UnsetMethod(); /** * Clears the '<code>onBehalfOfContentOwner</code>' attribute so it is no * longer set. */ void clear_on_behalf_of_content_owner() { _have_on_behalf_of_content_owner_ = false; client::ClearCppValueHelper(&on_behalf_of_content_owner_); } /** * Gets the optional '<code>onBehalfOfContentOwner</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_on_behalf_of_content_owner() const { return on_behalf_of_content_owner_; } /** * Gets a modifiable pointer to the optional * <code>onBehalfOfContentOwner</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_onBehalfOfContentOwner() { _have_on_behalf_of_content_owner_ = true; return &on_behalf_of_content_owner_; } /** * Sets the '<code>onBehalfOfContentOwner</code>' attribute. * * @param[in] value Note: This parameter is intended exclusively for YouTube * content partners. * * The onBehalfOfContentOwner parameter indicates that the request's * authorization credentials identify a YouTube CMS user who is acting on * behalf of the content owner specified in the parameter value. This * parameter is intended for YouTube content partners that own and manage * many different YouTube channels. It allows content owners to authenticate * once and get access to all their video and channel data, without having * to provide authentication credentials for each individual channel. The * CMS account that the user authenticates with must be linked to the * specified YouTube content owner. */ void set_on_behalf_of_content_owner(const string& value) { _have_on_behalf_of_content_owner_ = true; on_behalf_of_content_owner_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string channel_id_; string on_behalf_of_content_owner_; bool _have_on_behalf_of_content_owner_ : 1; DISALLOW_COPY_AND_ASSIGN(WatermarksResource_UnsetMethod); }; /** * Service definition for YouTubeService (v3). * * @ingroup ServiceClass * * For more information about this service, see the API Documentation at * <a href='https://developers.google.com/youtube/v3'>'https://developers.google.com/youtube/v3</a> */ class YouTubeService : public client::ClientService { public: /** * The name of the API that this was generated from. */ static const char googleapis_API_NAME[]; /** * The version of the API that this interface was generated from. */ static const char googleapis_API_VERSION[]; /** * The code generator used to generate this API. */ static const char googleapis_API_GENERATOR[]; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class ActivitiesResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit ActivitiesResource(YouTubeService* service); /** * Standard destructor. */ ~ActivitiesResource() {} /** * Creates a new ActivitiesResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ActivitiesResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const Activity& _content_) const; /** * Creates a new ActivitiesResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more activity resource properties that the API response will * include. * * If the parameter identifies a property that contains child properties, * the child properties will be included in the response. For example, in an * activity resource, the snippet property contains other properties that * identify the type of activity, a display title for the activity, and so * forth. If you set part=snippet, the API response will also contain all of * those nested properties. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ActivitiesResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more activity resource properties that the API response will * include. * * If the parameter identifies a property that contains child properties, * the child properties will be included in the response. For example, in an * activity resource, the snippet property contains other properties that * identify the type of activity, a display title for the activity, and so * forth. If you set part=snippet, the API response will also contain all of * those nested properties. * * * @see googleapis::googleapis::ServiceRequestPager */ ActivitiesResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& part) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(ActivitiesResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class CaptionsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit CaptionsResource(YouTubeService* service); /** * Standard destructor. */ ~CaptionsResource() {} /** * Creates a new CaptionsResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter identifies the caption track that is being * deleted. The value is a caption track ID as identified by the id property * in a caption resource. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CaptionsResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& id) const; /** * Creates a new CaptionsResource_DownloadMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter identifies the caption track that is being * retrieved. The value is a caption track ID as identified by the id * property in a caption resource. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CaptionsResource_DownloadMethod* NewDownloadMethod( client::AuthorizationCredential* _credential_, const StringPiece& id) const; /** * Creates a new CaptionsResource_InsertMethod instance. * @deprecated * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies the caption resource parts * that the API response will include. Set the parameter value to snippet. * * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CaptionsResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a new CaptionsResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies the caption resource parts * that the API response will include. Set the parameter value to snippet. * @param[in] _metadata_ The metadata object to insert. If this is NULL then * do not upload any metadata. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to insert. If * this is NULL then do not upload any media and ignore * _media_content_type_. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CaptionsResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const Caption* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const; /** * Creates a new CaptionsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more caption resource parts that the API response will include. * The part names that you can include in the parameter value are id and * snippet. * @param[in] video_id The videoId parameter specifies the YouTube video ID * of the video for which the API should return caption tracks. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CaptionsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const StringPiece& video_id) const; /** * Creates a new CaptionsResource_UpdateMethod instance. * @deprecated * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. Set the property value * to snippet if you are updating the track's draft status. Otherwise, set * the property value to id. * * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CaptionsResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a new CaptionsResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. Set the property value * to snippet if you are updating the track's draft status. Otherwise, set * the property value to id. * @param[in] _metadata_ The metadata object to update. If this is NULL then * do not upload any metadata. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to update. If * this is NULL then do not upload any media and ignore * _media_content_type_. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CaptionsResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const Caption* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(CaptionsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class ChannelBannersResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit ChannelBannersResource(YouTubeService* service); /** * Standard destructor. */ ~ChannelBannersResource() {} /** * Creates a new ChannelBannersResource_InsertMethod instance. * @deprecated * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChannelBannersResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_) const; /** * Creates a new ChannelBannersResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] _metadata_ The metadata object to insert. If this is NULL then * do not upload any metadata. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to insert. If * this is NULL then do not upload any media and ignore * _media_content_type_. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChannelBannersResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const ChannelBannerResource* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(ChannelBannersResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class ChannelSectionsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit ChannelSectionsResource(YouTubeService* service); /** * Standard destructor. */ ~ChannelSectionsResource() {} /** * Creates a new ChannelSectionsResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter specifies the YouTube channelSection ID * for the resource that is being deleted. In a channelSection resource, the * id property specifies the YouTube channelSection ID. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChannelSectionsResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& id) const; /** * Creates a new ChannelSectionsResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * The part names that you can include in the parameter value are snippet * and contentDetails. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChannelSectionsResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const ChannelSection& _content_) const; /** * Creates a new ChannelSectionsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more channelSection resource properties that the API response will * include. The part names that you can include in the parameter value are * id, snippet, and contentDetails. * * If the parameter identifies a property that contains child properties, * the child properties will be included in the response. For example, in a * channelSection resource, the snippet property contains other properties, * such as a display title for the channelSection. If you set part=snippet, * the API response will also contain all of those nested properties. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChannelSectionsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a new ChannelSectionsResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * The part names that you can include in the parameter value are snippet * and contentDetails. * @param[in] _content_ The data object to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChannelSectionsResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const ChannelSection& _content_) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(ChannelSectionsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class ChannelsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit ChannelsResource(YouTubeService* service); /** * Standard destructor. */ ~ChannelsResource() {} /** * Creates a new ChannelsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more channel resource properties that the API response will * include. * * If the parameter identifies a property that contains child properties, * the child properties will be included in the response. For example, in a * channel resource, the contentDetails property contains other properties, * such as the uploads properties. As such, if you set part=contentDetails, * the API response will also contain all of those nested properties. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChannelsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more channel resource properties that the API response will * include. * * If the parameter identifies a property that contains child properties, * the child properties will be included in the response. For example, in a * channel resource, the contentDetails property contains other properties, * such as the uploads properties. As such, if you set part=contentDetails, * the API response will also contain all of those nested properties. * * * @see googleapis::googleapis::ServiceRequestPager */ ChannelsResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a new ChannelsResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * The API currently only allows the parameter value to be set to either * brandingSettings or invideoPromotion. (You cannot update both of those * parts with a single request.) * * Note that this method overrides the existing values for all of the * mutable properties that are contained in any parts that the parameter * value specifies. * @param[in] _content_ The data object to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChannelsResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const Channel& _content_) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(ChannelsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class CommentThreadsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit CommentThreadsResource(YouTubeService* service); /** * Standard destructor. */ ~CommentThreadsResource() {} /** * Creates a new CommentThreadsResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter identifies the properties that the API * response will include. Set the parameter value to snippet. The snippet * part has a quota cost of 2 units. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CommentThreadsResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const CommentThread& _content_) const; /** * Creates a new CommentThreadsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more commentThread resource properties that the API response will * include. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CommentThreadsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more commentThread resource properties that the API response will * include. * * * @see googleapis::googleapis::ServiceRequestPager */ CommentThreadsResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a new CommentThreadsResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * commentThread resource properties that the API response will include. You * must at least include the snippet part in the parameter value since that * part contains all of the properties that the API request can update. * @param[in] _content_ The data object to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CommentThreadsResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const CommentThread& _content_) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(CommentThreadsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class CommentsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit CommentsResource(YouTubeService* service); /** * Standard destructor. */ ~CommentsResource() {} /** * Creates a new CommentsResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter specifies the comment ID for the resource * that is being deleted. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CommentsResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& id) const; /** * Creates a new CommentsResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter identifies the properties that the API * response will include. Set the parameter value to snippet. The snippet * part has a quota cost of 2 units. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CommentsResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const Comment& _content_) const; /** * Creates a new CommentsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more comment resource properties that the API response will * include. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CommentsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more comment resource properties that the API response will * include. * * * @see googleapis::googleapis::ServiceRequestPager */ CommentsResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a new CommentsResource_MarkAsSpamMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter specifies a comma-separated list of IDs of * comments that the caller believes should be classified as spam. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CommentsResource_MarkAsSpamMethod* NewMarkAsSpamMethod( client::AuthorizationCredential* _credential_, const StringPiece& id) const; /** * Creates a new CommentsResource_SetModerationStatusMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter specifies a comma-separated list of IDs * that identify the comments for which you are updating the moderation * status. * @param[in] moderation_status Identifies the new moderation status of the * specified comments. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CommentsResource_SetModerationStatusMethod* NewSetModerationStatusMethod( client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& moderation_status) const; /** * Creates a new CommentsResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter identifies the properties that the API * response will include. You must at least include the snippet part in the * parameter value since that part contains all of the properties that the * API request can update. * @param[in] _content_ The data object to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CommentsResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const Comment& _content_) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(CommentsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class FanFundingEventsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit FanFundingEventsResource(YouTubeService* service); /** * Standard destructor. */ ~FanFundingEventsResource() {} /** * Creates a new FanFundingEventsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies the fanFundingEvent resource * parts that the API response will include. Supported values are id and * snippet. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FanFundingEventsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] part The part parameter specifies the fanFundingEvent resource * parts that the API response will include. Supported values are id and * snippet. * * * @see googleapis::googleapis::ServiceRequestPager */ FanFundingEventsResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& part) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(FanFundingEventsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class GuideCategoriesResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit GuideCategoriesResource(YouTubeService* service); /** * Standard destructor. */ ~GuideCategoriesResource() {} /** * Creates a new GuideCategoriesResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies the guideCategory resource * properties that the API response will include. Set the parameter value to * snippet. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ GuideCategoriesResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(GuideCategoriesResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class I18nLanguagesResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit I18nLanguagesResource(YouTubeService* service); /** * Standard destructor. */ ~I18nLanguagesResource() {} /** * Creates a new I18nLanguagesResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies the i18nLanguage resource * properties that the API response will include. Set the parameter value to * snippet. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ I18nLanguagesResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(I18nLanguagesResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class I18nRegionsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit I18nRegionsResource(YouTubeService* service); /** * Standard destructor. */ ~I18nRegionsResource() {} /** * Creates a new I18nRegionsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies the i18nRegion resource * properties that the API response will include. Set the parameter value to * snippet. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ I18nRegionsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(I18nRegionsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class LiveBroadcastsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit LiveBroadcastsResource(YouTubeService* service); /** * Standard destructor. */ ~LiveBroadcastsResource() {} /** * Creates a new LiveBroadcastsResource_BindMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter specifies the unique ID of the broadcast * that is being bound to a video stream. * @param[in] part The part parameter specifies a comma-separated list of * one or more liveBroadcast resource properties that the API response will * include. The part names that you can include in the parameter value are * id, snippet, contentDetails, and status. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveBroadcastsResource_BindMethod* NewBindMethod( client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& part) const; /** * Creates a new LiveBroadcastsResource_ControlMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter specifies the YouTube live broadcast ID * that uniquely identifies the broadcast in which the slate is being * updated. * @param[in] part The part parameter specifies a comma-separated list of * one or more liveBroadcast resource properties that the API response will * include. The part names that you can include in the parameter value are * id, snippet, contentDetails, and status. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveBroadcastsResource_ControlMethod* NewControlMethod( client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& part) const; /** * Creates a new LiveBroadcastsResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter specifies the YouTube live broadcast ID * for the resource that is being deleted. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveBroadcastsResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& id) const; /** * Creates a new LiveBroadcastsResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * The part properties that you can include in the parameter value are id, * snippet, contentDetails, and status. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveBroadcastsResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveBroadcast& _content_) const; /** * Creates a new LiveBroadcastsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more liveBroadcast resource properties that the API response will * include. The part names that you can include in the parameter value are * id, snippet, contentDetails, and status. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveBroadcastsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more liveBroadcast resource properties that the API response will * include. The part names that you can include in the parameter value are * id, snippet, contentDetails, and status. * * * @see googleapis::googleapis::ServiceRequestPager */ LiveBroadcastsResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a new LiveBroadcastsResource_TransitionMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] broadcast_status The broadcastStatus parameter identifies the * state to which the broadcast is changing. Note that to transition a * broadcast to either the testing or live state, the status.streamStatus * must be active for the stream that the broadcast is bound to. * @param[in] id The id parameter specifies the unique ID of the broadcast * that is transitioning to another status. * @param[in] part The part parameter specifies a comma-separated list of * one or more liveBroadcast resource properties that the API response will * include. The part names that you can include in the parameter value are * id, snippet, contentDetails, and status. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveBroadcastsResource_TransitionMethod* NewTransitionMethod( client::AuthorizationCredential* _credential_, const StringPiece& broadcast_status, const StringPiece& id, const StringPiece& part) const; /** * Creates a new LiveBroadcastsResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * The part properties that you can include in the parameter value are id, * snippet, contentDetails, and status. * * Note that this method will override the existing values for all of the * mutable properties that are contained in any parts that the parameter * value specifies. For example, a broadcast's privacy status is defined in * the status part. As such, if your request is updating a private or * unlisted broadcast, and the request's part parameter value includes the * status part, the broadcast's privacy setting will be updated to whatever * value the request body specifies. If the request body does not specify a * value, the existing privacy setting will be removed and the broadcast * will revert to the default privacy setting. * @param[in] _content_ The data object to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveBroadcastsResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveBroadcast& _content_) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(LiveBroadcastsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class LiveChatBansResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit LiveChatBansResource(YouTubeService* service); /** * Standard destructor. */ ~LiveChatBansResource() {} /** * Creates a new LiveChatBansResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter identifies the chat ban to remove. The * value uniquely identifies both the ban and the chat. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveChatBansResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& id) const; /** * Creates a new LiveChatBansResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response returns. Set the parameter value to * snippet. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveChatBansResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveChatBan& _content_) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(LiveChatBansResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class LiveChatMessagesResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit LiveChatMessagesResource(YouTubeService* service); /** * Standard destructor. */ ~LiveChatMessagesResource() {} /** * Creates a new LiveChatMessagesResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter specifies the YouTube chat message ID of * the resource that is being deleted. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveChatMessagesResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& id) const; /** * Creates a new LiveChatMessagesResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes. It identifies the * properties that the write operation will set as well as the properties * that the API response will include. Set the parameter value to snippet. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveChatMessagesResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveChatMessage& _content_) const; /** * Creates a new LiveChatMessagesResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] live_chat_id The liveChatId parameter specifies the ID of the * chat whose messages will be returned. * @param[in] part The part parameter specifies the liveChatComment resource * parts that the API response will include. Supported values are id and * snippet. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveChatMessagesResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& live_chat_id, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] live_chat_id The liveChatId parameter specifies the ID of the * chat whose messages will be returned. * * @param[in] part The part parameter specifies the liveChatComment resource * parts that the API response will include. Supported values are id and * snippet. * * * @see googleapis::googleapis::ServiceRequestPager */ LiveChatMessagesResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& live_chat_id, const StringPiece& part) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(LiveChatMessagesResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class LiveChatModeratorsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit LiveChatModeratorsResource(YouTubeService* service); /** * Standard destructor. */ ~LiveChatModeratorsResource() {} /** * Creates a new LiveChatModeratorsResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter identifies the chat moderator to remove. * The value uniquely identifies both the moderator and the chat. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveChatModeratorsResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& id) const; /** * Creates a new LiveChatModeratorsResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response returns. Set the parameter value to * snippet. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveChatModeratorsResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveChatModerator& _content_) const; /** * Creates a new LiveChatModeratorsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] live_chat_id The liveChatId parameter specifies the YouTube * live chat for which the API should return moderators. * @param[in] part The part parameter specifies the liveChatModerator * resource parts that the API response will include. Supported values are * id and snippet. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveChatModeratorsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& live_chat_id, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] live_chat_id The liveChatId parameter specifies the YouTube * live chat for which the API should return moderators. * * @param[in] part The part parameter specifies the liveChatModerator * resource parts that the API response will include. Supported values are * id and snippet. * * * @see googleapis::googleapis::ServiceRequestPager */ LiveChatModeratorsResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& live_chat_id, const StringPiece& part) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(LiveChatModeratorsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class LiveStreamsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit LiveStreamsResource(YouTubeService* service); /** * Standard destructor. */ ~LiveStreamsResource() {} /** * Creates a new LiveStreamsResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter specifies the YouTube live stream ID for * the resource that is being deleted. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveStreamsResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& id) const; /** * Creates a new LiveStreamsResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * The part properties that you can include in the parameter value are id, * snippet, cdn, and status. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveStreamsResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveStream& _content_) const; /** * Creates a new LiveStreamsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more liveStream resource properties that the API response will * include. The part names that you can include in the parameter value are * id, snippet, cdn, and status. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveStreamsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more liveStream resource properties that the API response will * include. The part names that you can include in the parameter value are * id, snippet, cdn, and status. * * * @see googleapis::googleapis::ServiceRequestPager */ LiveStreamsResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a new LiveStreamsResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * The part properties that you can include in the parameter value are id, * snippet, cdn, and status. * * Note that this method will override the existing values for all of the * mutable properties that are contained in any parts that the parameter * value specifies. If the request body does not specify a value for a * mutable property, the existing value for that property will be removed. * @param[in] _content_ The data object to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ LiveStreamsResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveStream& _content_) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(LiveStreamsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class PlaylistItemsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit PlaylistItemsResource(YouTubeService* service); /** * Standard destructor. */ ~PlaylistItemsResource() {} /** * Creates a new PlaylistItemsResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter specifies the YouTube playlist item ID for * the playlist item that is being deleted. In a playlistItem resource, the * id property specifies the playlist item's ID. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PlaylistItemsResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& id) const; /** * Creates a new PlaylistItemsResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PlaylistItemsResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const PlaylistItem& _content_) const; /** * Creates a new PlaylistItemsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more playlistItem resource properties that the API response will * include. * * If the parameter identifies a property that contains child properties, * the child properties will be included in the response. For example, in a * playlistItem resource, the snippet property contains numerous fields, * including the title, description, position, and resourceId properties. As * such, if you set part=snippet, the API response will contain all of those * properties. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PlaylistItemsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more playlistItem resource properties that the API response will * include. * * If the parameter identifies a property that contains child properties, * the child properties will be included in the response. For example, in a * playlistItem resource, the snippet property contains numerous fields, * including the title, description, position, and resourceId properties. As * such, if you set part=snippet, the API response will contain all of those * properties. * * * @see googleapis::googleapis::ServiceRequestPager */ PlaylistItemsResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a new PlaylistItemsResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * Note that this method will override the existing values for all of the * mutable properties that are contained in any parts that the parameter * value specifies. For example, a playlist item can specify a start time * and end time, which identify the times portion of the video that should * play when users watch the video in the playlist. If your request is * updating a playlist item that sets these values, and the request's part * parameter value includes the contentDetails part, the playlist item's * start and end times will be updated to whatever value the request body * specifies. If the request body does not specify values, the existing * start and end times will be removed and replaced with the default * settings. * @param[in] _content_ The data object to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PlaylistItemsResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const PlaylistItem& _content_) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(PlaylistItemsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class PlaylistsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit PlaylistsResource(YouTubeService* service); /** * Standard destructor. */ ~PlaylistsResource() {} /** * Creates a new PlaylistsResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter specifies the YouTube playlist ID for the * playlist that is being deleted. In a playlist resource, the id property * specifies the playlist's ID. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PlaylistsResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& id) const; /** * Creates a new PlaylistsResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PlaylistsResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const Playlist& _content_) const; /** * Creates a new PlaylistsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more playlist resource properties that the API response will * include. * * If the parameter identifies a property that contains child properties, * the child properties will be included in the response. For example, in a * playlist resource, the snippet property contains properties like author, * title, description, tags, and timeCreated. As such, if you set * part=snippet, the API response will contain all of those properties. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PlaylistsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more playlist resource properties that the API response will * include. * * If the parameter identifies a property that contains child properties, * the child properties will be included in the response. For example, in a * playlist resource, the snippet property contains properties like author, * title, description, tags, and timeCreated. As such, if you set * part=snippet, the API response will contain all of those properties. * * * @see googleapis::googleapis::ServiceRequestPager */ PlaylistsResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a new PlaylistsResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * Note that this method will override the existing values for mutable * properties that are contained in any parts that the request body * specifies. For example, a playlist's description is contained in the * snippet part, which must be included in the request body. If the request * does not specify a value for the snippet.description property, the * playlist's existing description will be deleted. * @param[in] _content_ The data object to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PlaylistsResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const Playlist& _content_) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(PlaylistsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class SearchResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit SearchResource(YouTubeService* service); /** * Standard destructor. */ ~SearchResource() {} /** * Creates a new SearchResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more search resource properties that the API response will * include. Set the parameter value to snippet. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ SearchResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more search resource properties that the API response will * include. Set the parameter value to snippet. * * * @see googleapis::googleapis::ServiceRequestPager */ SearchResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& part) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(SearchResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class SponsorsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit SponsorsResource(YouTubeService* service); /** * Standard destructor. */ ~SponsorsResource() {} /** * Creates a new SponsorsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies the sponsor resource parts * that the API response will include. Supported values are id and snippet. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ SponsorsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] part The part parameter specifies the sponsor resource parts * that the API response will include. Supported values are id and snippet. * * * @see googleapis::googleapis::ServiceRequestPager */ SponsorsResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& part) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(SponsorsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class SubscriptionsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit SubscriptionsResource(YouTubeService* service); /** * Standard destructor. */ ~SubscriptionsResource() {} /** * Creates a new SubscriptionsResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter specifies the YouTube subscription ID for * the resource that is being deleted. In a subscription resource, the id * property specifies the YouTube subscription ID. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ SubscriptionsResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& id) const; /** * Creates a new SubscriptionsResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ SubscriptionsResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const Subscription& _content_) const; /** * Creates a new SubscriptionsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more subscription resource properties that the API response will * include. * * If the parameter identifies a property that contains child properties, * the child properties will be included in the response. For example, in a * subscription resource, the snippet property contains other properties, * such as a display title for the subscription. If you set part=snippet, * the API response will also contain all of those nested properties. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ SubscriptionsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more subscription resource properties that the API response will * include. * * If the parameter identifies a property that contains child properties, * the child properties will be included in the response. For example, in a * subscription resource, the snippet property contains other properties, * such as a display title for the subscription. If you set part=snippet, * the API response will also contain all of those nested properties. * * * @see googleapis::googleapis::ServiceRequestPager */ SubscriptionsResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& part) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(SubscriptionsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class SuperChatEventsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit SuperChatEventsResource(YouTubeService* service); /** * Standard destructor. */ ~SuperChatEventsResource() {} /** * Creates a new SuperChatEventsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies the superChatEvent resource * parts that the API response will include. Supported values are id and * snippet. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ SuperChatEventsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] part The part parameter specifies the superChatEvent resource * parts that the API response will include. Supported values are id and * snippet. * * * @see googleapis::googleapis::ServiceRequestPager */ SuperChatEventsResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& part) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(SuperChatEventsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class ThumbnailsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit ThumbnailsResource(YouTubeService* service); /** * Standard destructor. */ ~ThumbnailsResource() {} /** * Creates a new ThumbnailsResource_SetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] video_id The videoId parameter specifies a YouTube video ID * for which the custom video thumbnail is being provided. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to set. If * this is NULL then do not upload any media and ignore * _media_content_type_. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ThumbnailsResource_SetMethod* NewSetMethod( client::AuthorizationCredential* _credential_, const StringPiece& video_id, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(ThumbnailsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class VideoAbuseReportReasonsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit VideoAbuseReportReasonsResource(YouTubeService* service); /** * Standard destructor. */ ~VideoAbuseReportReasonsResource() {} /** * Creates a new VideoAbuseReportReasonsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies the videoCategory resource * parts that the API response will include. Supported values are id and * snippet. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ VideoAbuseReportReasonsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(VideoAbuseReportReasonsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class VideoCategoriesResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit VideoCategoriesResource(YouTubeService* service); /** * Standard destructor. */ ~VideoCategoriesResource() {} /** * Creates a new VideoCategoriesResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies the videoCategory resource * properties that the API response will include. Set the parameter value to * snippet. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ VideoCategoriesResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(VideoCategoriesResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class VideosResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit VideosResource(YouTubeService* service); /** * Standard destructor. */ ~VideosResource() {} /** * Creates a new VideosResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter specifies the YouTube video ID for the * resource that is being deleted. In a video resource, the id property * specifies the video's ID. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ VideosResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& id) const; /** * Creates a new VideosResource_GetRatingMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter specifies a comma-separated list of the * YouTube video ID(s) for the resource(s) for which you are retrieving * rating data. In a video resource, the id property specifies the video's * ID. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ VideosResource_GetRatingMethod* NewGetRatingMethod( client::AuthorizationCredential* _credential_, const StringPiece& id) const; /** * Creates a new VideosResource_InsertMethod instance. * @deprecated * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * Note that not all parts contain properties that can be set when inserting * or updating a video. For example, the statistics object encapsulates * statistics that YouTube calculates for a video and does not contain * values that you can set or modify. If the parameter value specifies a * part that does not contain mutable values, that part will still be * included in the API response. * * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ VideosResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a new VideosResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * Note that not all parts contain properties that can be set when inserting * or updating a video. For example, the statistics object encapsulates * statistics that YouTube calculates for a video and does not contain * values that you can set or modify. If the parameter value specifies a * part that does not contain mutable values, that part will still be * included in the API response. * @param[in] _metadata_ The metadata object to insert. If this is NULL then * do not upload any metadata. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to insert. If * this is NULL then do not upload any media and ignore * _media_content_type_. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ VideosResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const Video* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const; /** * Creates a new VideosResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more video resource properties that the API response will include. * * If the parameter identifies a property that contains child properties, * the child properties will be included in the response. For example, in a * video resource, the snippet property contains the channelId, title, * description, tags, and categoryId properties. As such, if you set * part=snippet, the API response will contain all of those properties. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ VideosResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] part The part parameter specifies a comma-separated list of * one or more video resource properties that the API response will include. * * If the parameter identifies a property that contains child properties, * the child properties will be included in the response. For example, in a * video resource, the snippet property contains the channelId, title, * description, tags, and categoryId properties. As such, if you set * part=snippet, the API response will contain all of those properties. * * * @see googleapis::googleapis::ServiceRequestPager */ VideosResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& part) const; /** * Creates a new VideosResource_RateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] id The id parameter specifies the YouTube video ID of the * video that is being rated or having its rating removed. * @param[in] rating Specifies the rating to record. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ VideosResource_RateMethod* NewRateMethod( client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& rating) const; /** * Creates a new VideosResource_ReportAbuseMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] _content_ The data object to reportAbuse. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ VideosResource_ReportAbuseMethod* NewReportAbuseMethod( client::AuthorizationCredential* _credential_, const VideoAbuseReport& _content_) const; /** * Creates a new VideosResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] part The part parameter serves two purposes in this operation. * It identifies the properties that the write operation will set as well as * the properties that the API response will include. * * Note that this method will override the existing values for all of the * mutable properties that are contained in any parts that the parameter * value specifies. For example, a video's privacy setting is contained in * the status part. As such, if your request is updating a private video, * and the request's part parameter value includes the status part, the * video's privacy setting will be updated to whatever value the request * body specifies. If the request body does not specify a value, the * existing privacy setting will be removed and the video will revert to the * default privacy setting. * * In addition, not all parts contain properties that can be set when * inserting or updating a video. For example, the statistics object * encapsulates statistics that YouTube calculates for a video and does not * contain values that you can set or modify. If the parameter value * specifies a part that does not contain mutable values, that part will * still be included in the API response. * @param[in] _content_ The data object to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ VideosResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& part, const Video& _content_) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(VideosResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class WatermarksResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit WatermarksResource(YouTubeService* service); /** * Standard destructor. */ ~WatermarksResource() {} /** * Creates a new WatermarksResource_SetMethod instance. * @deprecated * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] channel_id The channelId parameter specifies the YouTube * channel ID for which the watermark is being provided. * * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ WatermarksResource_SetMethod* NewSetMethod( client::AuthorizationCredential* _credential_, const StringPiece& channel_id) const; /** * Creates a new WatermarksResource_SetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] channel_id The channelId parameter specifies the YouTube * channel ID for which the watermark is being provided. * @param[in] _metadata_ The metadata object to set. If this is NULL then do * not upload any metadata. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to set. If * this is NULL then do not upload any media and ignore * _media_content_type_. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ WatermarksResource_SetMethod* NewSetMethod( client::AuthorizationCredential* _credential_, const StringPiece& channel_id, const InvideoBranding* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const; /** * Creates a new WatermarksResource_UnsetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] channel_id The channelId parameter specifies the YouTube * channel ID for which the watermark is being unset. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ WatermarksResource_UnsetMethod* NewUnsetMethod( client::AuthorizationCredential* _credential_, const StringPiece& channel_id) const; private: YouTubeService* service_; DISALLOW_COPY_AND_ASSIGN(WatermarksResource); }; /** * Standard constructor. * * @param[in] transport The transport to use when creating methods to invoke * on this service instance. */ explicit YouTubeService(client::HttpTransport* transport); /** * Standard destructor. */ virtual ~YouTubeService(); /** * Gets the resource method factory. * * @return ActivitiesResource for creating methods. */ const ActivitiesResource& get_activities() const { return activities_; } /** * Gets the resource method factory. * * @return CaptionsResource for creating methods. */ const CaptionsResource& get_captions() const { return captions_; } /** * Gets the resource method factory. * * @return ChannelBannersResource for creating methods. */ const ChannelBannersResource& get_channel_banners() const { return channel_banners_; } /** * Gets the resource method factory. * * @return ChannelSectionsResource for creating methods. */ const ChannelSectionsResource& get_channel_sections() const { return channel_sections_; } /** * Gets the resource method factory. * * @return ChannelsResource for creating methods. */ const ChannelsResource& get_channels() const { return channels_; } /** * Gets the resource method factory. * * @return CommentThreadsResource for creating methods. */ const CommentThreadsResource& get_comment_threads() const { return comment_threads_; } /** * Gets the resource method factory. * * @return CommentsResource for creating methods. */ const CommentsResource& get_comments() const { return comments_; } /** * Gets the resource method factory. * * @return FanFundingEventsResource for creating methods. */ const FanFundingEventsResource& get_fan_funding_events() const { return fan_funding_events_; } /** * Gets the resource method factory. * * @return GuideCategoriesResource for creating methods. */ const GuideCategoriesResource& get_guide_categories() const { return guide_categories_; } /** * Gets the resource method factory. * * @return I18nLanguagesResource for creating methods. */ const I18nLanguagesResource& get_i18n_languages() const { return i18n_languages_; } /** * Gets the resource method factory. * * @return I18nRegionsResource for creating methods. */ const I18nRegionsResource& get_i18n_regions() const { return i18n_regions_; } /** * Gets the resource method factory. * * @return LiveBroadcastsResource for creating methods. */ const LiveBroadcastsResource& get_live_broadcasts() const { return live_broadcasts_; } /** * Gets the resource method factory. * * @return LiveChatBansResource for creating methods. */ const LiveChatBansResource& get_live_chat_bans() const { return live_chat_bans_; } /** * Gets the resource method factory. * * @return LiveChatMessagesResource for creating methods. */ const LiveChatMessagesResource& get_live_chat_messages() const { return live_chat_messages_; } /** * Gets the resource method factory. * * @return LiveChatModeratorsResource for creating methods. */ const LiveChatModeratorsResource& get_live_chat_moderators() const { return live_chat_moderators_; } /** * Gets the resource method factory. * * @return LiveStreamsResource for creating methods. */ const LiveStreamsResource& get_live_streams() const { return live_streams_; } /** * Gets the resource method factory. * * @return PlaylistItemsResource for creating methods. */ const PlaylistItemsResource& get_playlist_items() const { return playlist_items_; } /** * Gets the resource method factory. * * @return PlaylistsResource for creating methods. */ const PlaylistsResource& get_playlists() const { return playlists_; } /** * Gets the resource method factory. * * @return SearchResource for creating methods. */ const SearchResource& get_search() const { return search_; } /** * Gets the resource method factory. * * @return SponsorsResource for creating methods. */ const SponsorsResource& get_sponsors() const { return sponsors_; } /** * Gets the resource method factory. * * @return SubscriptionsResource for creating methods. */ const SubscriptionsResource& get_subscriptions() const { return subscriptions_; } /** * Gets the resource method factory. * * @return SuperChatEventsResource for creating methods. */ const SuperChatEventsResource& get_super_chat_events() const { return super_chat_events_; } /** * Gets the resource method factory. * * @return ThumbnailsResource for creating methods. */ const ThumbnailsResource& get_thumbnails() const { return thumbnails_; } /** * Gets the resource method factory. * * @return VideoAbuseReportReasonsResource for creating methods. */ const VideoAbuseReportReasonsResource& get_video_abuse_report_reasons() const { return video_abuse_report_reasons_; } /** * Gets the resource method factory. * * @return VideoCategoriesResource for creating methods. */ const VideoCategoriesResource& get_video_categories() const { return video_categories_; } /** * Gets the resource method factory. * * @return VideosResource for creating methods. */ const VideosResource& get_videos() const { return videos_; } /** * Gets the resource method factory. * * @return WatermarksResource for creating methods. */ const WatermarksResource& get_watermarks() const { return watermarks_; } /** * Declares the OAuth2.0 scopes used within YouTube Data API * * These scopes shoudl be used when asking for credentials to invoke methods * in the YouTubeService. */ class SCOPES { public: /** * Manage your YouTube account. */ static const char YOUTUBE[]; /** * Manage your YouTube account. */ static const char YOUTUBE_FORCE_SSL[]; /** * View your YouTube account. */ static const char YOUTUBE_READONLY[]; /** * Manage your YouTube videos. */ static const char YOUTUBE_UPLOAD[]; /** * View and manage your assets and associated content on YouTube. */ static const char YOUTUBEPARTNER[]; /** * View private information of your YouTube channel relevant during the * audit process with a YouTube partner. */ static const char YOUTUBEPARTNER_CHANNEL_AUDIT[]; private: SCOPES(); // Never instantiated. ~SCOPES(); // Never instantiated. }; private: ActivitiesResource activities_; CaptionsResource captions_; ChannelBannersResource channel_banners_; ChannelSectionsResource channel_sections_; ChannelsResource channels_; CommentThreadsResource comment_threads_; CommentsResource comments_; FanFundingEventsResource fan_funding_events_; GuideCategoriesResource guide_categories_; I18nLanguagesResource i18n_languages_; I18nRegionsResource i18n_regions_; LiveBroadcastsResource live_broadcasts_; LiveChatBansResource live_chat_bans_; LiveChatMessagesResource live_chat_messages_; LiveChatModeratorsResource live_chat_moderators_; LiveStreamsResource live_streams_; PlaylistItemsResource playlist_items_; PlaylistsResource playlists_; SearchResource search_; SponsorsResource sponsors_; SubscriptionsResource subscriptions_; SuperChatEventsResource super_chat_events_; ThumbnailsResource thumbnails_; VideoAbuseReportReasonsResource video_abuse_report_reasons_; VideoCategoriesResource video_categories_; VideosResource videos_; WatermarksResource watermarks_; DISALLOW_COPY_AND_ASSIGN(YouTubeService); }; /** * @defgroup DataObject YouTube Data API Data Objects * * The data objects are used as parameters and responses from service requests. * For more information about using data objects, see the * <a href='https://developers.google.com/api-client-library/cpp/'> * Google APIs Client Library for C++ Developers's Guide</a>. */ /** * @defgroup ServiceClass YouTube Data API Service * * The service classes contain information about accessing and using the * YouTube Data API cloud service. * * For more information about using services, see the * <a href='https://developers.google.com/api-client-library/cpp/'> * Google APIs Client Library for C++ Developers's Guide</a>. */ /** * @defgroup ServiceMethod YouTube Data API Service Methods * * The service method classes are used to create and invoke methods in the * YouTubeService to access the YouTube Data API. * * For more information about using services, see the * <a href='https://developers.google.com/api-client-library/cpp/'> * Google APIs Client Library for C++ Developers's Guide</a>. */ } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_YOU_TUBE_SERVICE_H_ <file_sep>/src/samples/abstract_login_flow.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <string> using std::string; #include "samples/abstract_login_flow.h" #include "googleapis/client/auth/oauth2_authorization.h" #include "googleapis/client/transport/http_request.h" #include "googleapis/client/transport/http_types.h" #include "googleapis/client/util/abstract_webserver.h" #include "googleapis/client/util/status.h" #include "googleapis/base/callback.h" #include <glog/logging.h> #include "googleapis/strings/strcat.h" #include "googleapis/util/hash.h" namespace googleapis { using client::AbstractWebServer; using client::OAuth2AuthorizationFlow; using client::OAuth2RequestOptions; using client::OAuth2Credential; using client::HttpStatusCode; using client::ParsedUrl; using client::WebServerRequest; using client::WebServerResponse; using client::StatusUnknown; namespace sample { AbstractLoginFlow::AbstractLoginFlow( const string& cookie_name, const string& redirect_name, OAuth2AuthorizationFlow* flow) : cookie_name_(cookie_name), redirect_name_(redirect_name), flow_(flow) { } AbstractLoginFlow::~AbstractLoginFlow() { } void AbstractLoginFlow::AddLoginUrl( const string& url, AbstractWebServer* httpd) { CHECK(login_url_.empty()); login_url_ = url; httpd->AddPathHandler( login_url_, NewPermanentCallback( this, &AbstractLoginFlow::HandleLoginUrl)); } void AbstractLoginFlow::AddLogoutUrl( const string& url, AbstractWebServer* httpd) { CHECK(logout_url_.empty()); logout_url_ = url; httpd->AddPathHandler( logout_url_, NewPermanentCallback( this, &AbstractLoginFlow::HandleLogoutUrl)); } void AbstractLoginFlow::AddReceiveAccessTokenUrl( const string& url, AbstractWebServer* httpd) { CHECK(access_token_url_.empty()); access_token_url_ = url; httpd->AddPathHandler( access_token_url_, NewPermanentCallback( this, &AbstractLoginFlow::HandleAccessTokenUrl)); } util::Status AbstractLoginFlow::ReceiveAuthorizationCode( const string& cookie_id, const string& want_url, WebServerRequest* request) { string error; string code; const ParsedUrl& parsed_url = request->parsed_url(); bool have_code = parsed_url.GetQueryParameter("code", &code); bool have_error = parsed_url.GetQueryParameter("error", &error); googleapis::util::Status status; if (have_error) { status = StatusUnknown(StrCat("Did not authorize: ", error)); } else if (!have_code) { status = StatusUnknown("Missing authorization code"); } OAuth2Credential* new_credential = NULL; if (status.ok()) { LOG(INFO) << "Received AuthorizationCode for cookie=" << cookie_id; OAuth2RequestOptions options; std::unique_ptr<OAuth2Credential> credential(flow_->NewCredential()); status = flow_->PerformExchangeAuthorizationCode( code, options, credential.get()); if (status.ok()) { LOG(INFO) << "Got credential for cookie=" << cookie_id; new_credential = credential.release(); } else { LOG(INFO) << "Failed to get credential for cookie=" << cookie_id; } } DoReceiveCredentialForCookieId(cookie_id, status, new_credential); if (!want_url.empty()) { LOG(INFO) << "Restoring continuation for cookie=" << cookie_id; if (status.ok()) { return RedirectToUrl(want_url, cookie_id, request); } else { return DoRespondWithLoginErrorPage(cookie_id, status, request); } } else { return DoRespondWithWelcomePage(cookie_id, request); } } util::Status AbstractLoginFlow::InitiateAuthorizationFlow( WebServerRequest* request, const string& redirect_url) { return DoInitiateAuthorizationFlow(request, redirect_url); } util::Status AbstractLoginFlow::HandleAccessTokenUrl( WebServerRequest* request) { return DoHandleAccessTokenUrl(request); } util::Status AbstractLoginFlow::DoHandleAccessTokenUrl( WebServerRequest* request) { string cookie_id; string access_token; string msg; string error; int http_code; const ParsedUrl& parsed_url = request->parsed_url(); if (!parsed_url.GetQueryParameter("access_token", &access_token)) { http_code = HttpStatusCode::BAD_REQUEST; msg = "No access_token provided"; } else if (!parsed_url.GetQueryParameter("state", &cookie_id) || cookie_id.empty()) { http_code = HttpStatusCode::BAD_REQUEST; msg = "No state param"; } else if (access_token.empty()) { http_code = HttpStatusCode::OK; msg = "Revoked permissions"; DoReceiveCredentialForCookieId( cookie_id, client::StatusOk(), NULL); } else { OAuth2Credential* credential = flow_->NewCredential(); credential->set_access_token(access_token); googleapis::util::Status status; if (!DoReceiveCredentialForCookieId( cookie_id, client::StatusOk(), credential)) { msg = "LOGIN"; } else { msg = "Welcome back."; } http_code = 200; } return request->response()->SendText(http_code, msg); } util::Status AbstractLoginFlow::HandleLoginUrl(WebServerRequest* request) { return DoHandleLoginUrl(request); } util::Status AbstractLoginFlow::DoHandleLoginUrl(WebServerRequest* request) { VLOG(1) << "Handling " << request->parsed_url().url(); const string& cookie_id = GetCookieId(request); OAuth2Credential* credential = DoGetCredentialForCookieId(cookie_id); string redirect_url; request->parsed_url().GetQueryParameter(redirect_name_, &redirect_url); if (credential) { if (!redirect_url.empty()) { return RedirectToUrl(redirect_url, cookie_id, request); } if (!credential->access_token().empty()) { return DoRespondWithWelcomePage(cookie_id, request); } } if (redirect_url.empty()) { return DoRespondWithNotLoggedInPage(cookie_id, request); } return InitiateAuthorizationFlow(request, redirect_url); } util::Status AbstractLoginFlow::HandleLogoutUrl(WebServerRequest* request) { return DoHandleLogoutUrl(request); } util::Status AbstractLoginFlow::DoHandleLogoutUrl( WebServerRequest* request) { VLOG(1) << "Handling " << request->parsed_url().url(); const string& cookie_id = GetCookieId(request); OAuth2Credential* credential = DoGetCredentialForCookieId(cookie_id); if (!credential) { VLOG(1) << "Ignored because there was no known credential to revoke."; } else { string access_token; string refresh_token; credential->access_token().AppendTo(&access_token); credential->refresh_token().AppendTo(&refresh_token); if (access_token.empty() && refresh_token.empty()) { VLOG(1) << "Not logged into sample app yet"; } else { googleapis::util::Status status = flow_->PerformRevokeToken(refresh_token.empty(), credential); VLOG(1) << "Clearing credential for " << cookie_id; DoReceiveCredentialForCookieId( cookie_id, client::StatusOk(), NULL); if (status.ok()) { VLOG(1) << "Revoked " << (refresh_token.empty() ? "Access" : "Refresh") << "Token"; } else { LOG(ERROR) << status.error_message(); } } } return RedirectToUrl(login_url_, cookie_id, request); } // Responds to a request by redirecting to a url. util::Status AbstractLoginFlow::RedirectToUrl( const string& url, const string& cookie_id, WebServerRequest* request) { LOG(INFO) << "Redirecting cookie=" << cookie_id << " to " << url; WebServerResponse* response = request->response(); googleapis::util::Status status = response->AddCookie(cookie_name_, cookie_id); if (!status.ok()) return status; return response->SendRedirect(HttpStatusCode::TEMPORARY_REDIRECT, url); } string AbstractLoginFlow::GetCookieId(WebServerRequest* request) { string cookie; if (!request->GetCookieValue(cookie_name_.c_str(), &cookie)) { VLOG(1) << "Missing cookie_id cookie=" << cookie_name_; } return cookie; } } // namespace sample } // namespace googleapis <file_sep>/service_apis/youtube/google/youtube_api/video_processing_details.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_VIDEO_PROCESSING_DETAILS_H_ #define GOOGLE_YOUTUBE_API_VIDEO_PROCESSING_DETAILS_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/video_processing_details_processing_progress.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Describes processing status and progress and availability of some other Video * resource parts. * * @ingroup DataObject */ class VideoProcessingDetails : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static VideoProcessingDetails* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoProcessingDetails(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoProcessingDetails(Json::Value* storage); /** * Standard destructor. */ virtual ~VideoProcessingDetails(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::VideoProcessingDetails</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::VideoProcessingDetails"); } /** * Determine if the '<code>editorSuggestionsAvailability</code>' attribute was * set. * * @return true if the '<code>editorSuggestionsAvailability</code>' attribute * was set. */ bool has_editor_suggestions_availability() const { return Storage().isMember("editorSuggestionsAvailability"); } /** * Clears the '<code>editorSuggestionsAvailability</code>' attribute. */ void clear_editor_suggestions_availability() { MutableStorage()->removeMember("editorSuggestionsAvailability"); } /** * Get the value of the '<code>editorSuggestionsAvailability</code>' * attribute. */ const StringPiece get_editor_suggestions_availability() const { const Json::Value& v = Storage("editorSuggestionsAvailability"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>editorSuggestionsAvailability</code>' attribute. * * This value indicates whether video editing suggestions, which might improve * video quality or the playback experience, are available for the video. You * can retrieve these suggestions by requesting the suggestions part in your * videos.list() request. * * @param[in] value The new value. */ void set_editor_suggestions_availability(const StringPiece& value) { *MutableStorage("editorSuggestionsAvailability") = value.data(); } /** * Determine if the '<code>fileDetailsAvailability</code>' attribute was set. * * @return true if the '<code>fileDetailsAvailability</code>' attribute was * set. */ bool has_file_details_availability() const { return Storage().isMember("fileDetailsAvailability"); } /** * Clears the '<code>fileDetailsAvailability</code>' attribute. */ void clear_file_details_availability() { MutableStorage()->removeMember("fileDetailsAvailability"); } /** * Get the value of the '<code>fileDetailsAvailability</code>' attribute. */ const StringPiece get_file_details_availability() const { const Json::Value& v = Storage("fileDetailsAvailability"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>fileDetailsAvailability</code>' attribute. * * This value indicates whether file details are available for the uploaded * video. You can retrieve a video's file details by requesting the * fileDetails part in your videos.list() request. * * @param[in] value The new value. */ void set_file_details_availability(const StringPiece& value) { *MutableStorage("fileDetailsAvailability") = value.data(); } /** * Determine if the '<code>processingFailureReason</code>' attribute was set. * * @return true if the '<code>processingFailureReason</code>' attribute was * set. */ bool has_processing_failure_reason() const { return Storage().isMember("processingFailureReason"); } /** * Clears the '<code>processingFailureReason</code>' attribute. */ void clear_processing_failure_reason() { MutableStorage()->removeMember("processingFailureReason"); } /** * Get the value of the '<code>processingFailureReason</code>' attribute. */ const StringPiece get_processing_failure_reason() const { const Json::Value& v = Storage("processingFailureReason"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>processingFailureReason</code>' attribute. * * The reason that YouTube failed to process the video. This property will * only have a value if the processingStatus property's value is failed. * * @param[in] value The new value. */ void set_processing_failure_reason(const StringPiece& value) { *MutableStorage("processingFailureReason") = value.data(); } /** * Determine if the '<code>processingIssuesAvailability</code>' attribute was * set. * * @return true if the '<code>processingIssuesAvailability</code>' attribute * was set. */ bool has_processing_issues_availability() const { return Storage().isMember("processingIssuesAvailability"); } /** * Clears the '<code>processingIssuesAvailability</code>' attribute. */ void clear_processing_issues_availability() { MutableStorage()->removeMember("processingIssuesAvailability"); } /** * Get the value of the '<code>processingIssuesAvailability</code>' attribute. */ const StringPiece get_processing_issues_availability() const { const Json::Value& v = Storage("processingIssuesAvailability"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>processingIssuesAvailability</code>' attribute. * * This value indicates whether the video processing engine has generated * suggestions that might improve YouTube's ability to process the the video, * warnings that explain video processing problems, or errors that cause video * processing problems. You can retrieve these suggestions by requesting the * suggestions part in your videos.list() request. * * @param[in] value The new value. */ void set_processing_issues_availability(const StringPiece& value) { *MutableStorage("processingIssuesAvailability") = value.data(); } /** * Determine if the '<code>processingProgress</code>' attribute was set. * * @return true if the '<code>processingProgress</code>' attribute was set. */ bool has_processing_progress() const { return Storage().isMember("processingProgress"); } /** * Clears the '<code>processingProgress</code>' attribute. */ void clear_processing_progress() { MutableStorage()->removeMember("processingProgress"); } /** * Get a reference to the value of the '<code>processingProgress</code>' * attribute. */ const VideoProcessingDetailsProcessingProgress get_processing_progress() const; /** * Gets a reference to a mutable value of the * '<code>processingProgress</code>' property. * * The processingProgress object contains information about the progress * YouTube has made in processing the video. The values are really only * relevant if the video's processing status is processing. * * @return The result can be modified to change the attribute value. */ VideoProcessingDetailsProcessingProgress mutable_processingProgress(); /** * Determine if the '<code>processingStatus</code>' attribute was set. * * @return true if the '<code>processingStatus</code>' attribute was set. */ bool has_processing_status() const { return Storage().isMember("processingStatus"); } /** * Clears the '<code>processingStatus</code>' attribute. */ void clear_processing_status() { MutableStorage()->removeMember("processingStatus"); } /** * Get the value of the '<code>processingStatus</code>' attribute. */ const StringPiece get_processing_status() const { const Json::Value& v = Storage("processingStatus"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>processingStatus</code>' attribute. * * The video's processing status. This value indicates whether YouTube was * able to process the video or if the video is still being processed. * * @param[in] value The new value. */ void set_processing_status(const StringPiece& value) { *MutableStorage("processingStatus") = value.data(); } /** * Determine if the '<code>tagSuggestionsAvailability</code>' attribute was * set. * * @return true if the '<code>tagSuggestionsAvailability</code>' attribute was * set. */ bool has_tag_suggestions_availability() const { return Storage().isMember("tagSuggestionsAvailability"); } /** * Clears the '<code>tagSuggestionsAvailability</code>' attribute. */ void clear_tag_suggestions_availability() { MutableStorage()->removeMember("tagSuggestionsAvailability"); } /** * Get the value of the '<code>tagSuggestionsAvailability</code>' attribute. */ const StringPiece get_tag_suggestions_availability() const { const Json::Value& v = Storage("tagSuggestionsAvailability"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>tagSuggestionsAvailability</code>' attribute. * * This value indicates whether keyword (tag) suggestions are available for * the video. Tags can be added to a video's metadata to make it easier for * other users to find the video. You can retrieve these suggestions by * requesting the suggestions part in your videos.list() request. * * @param[in] value The new value. */ void set_tag_suggestions_availability(const StringPiece& value) { *MutableStorage("tagSuggestionsAvailability") = value.data(); } /** * Determine if the '<code>thumbnailsAvailability</code>' attribute was set. * * @return true if the '<code>thumbnailsAvailability</code>' attribute was * set. */ bool has_thumbnails_availability() const { return Storage().isMember("thumbnailsAvailability"); } /** * Clears the '<code>thumbnailsAvailability</code>' attribute. */ void clear_thumbnails_availability() { MutableStorage()->removeMember("thumbnailsAvailability"); } /** * Get the value of the '<code>thumbnailsAvailability</code>' attribute. */ const StringPiece get_thumbnails_availability() const { const Json::Value& v = Storage("thumbnailsAvailability"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>thumbnailsAvailability</code>' attribute. * * This value indicates whether thumbnail images have been generated for the * video. * * @param[in] value The new value. */ void set_thumbnails_availability(const StringPiece& value) { *MutableStorage("thumbnailsAvailability") = value.data(); } private: void operator=(const VideoProcessingDetails&); }; // VideoProcessingDetails } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_VIDEO_PROCESSING_DETAILS_H_ <file_sep>/service_apis/youtube/google/youtube_api/video_suggestions.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_VIDEO_SUGGESTIONS_H_ #define GOOGLE_YOUTUBE_API_VIDEO_SUGGESTIONS_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/video_suggestions_tag_suggestion.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Specifies suggestions on how to improve video content, including encoding * hints, tag suggestions, and editor suggestions. * * @ingroup DataObject */ class VideoSuggestions : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static VideoSuggestions* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoSuggestions(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoSuggestions(Json::Value* storage); /** * Standard destructor. */ virtual ~VideoSuggestions(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::VideoSuggestions</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::VideoSuggestions"); } /** * Determine if the '<code>editorSuggestions</code>' attribute was set. * * @return true if the '<code>editorSuggestions</code>' attribute was set. */ bool has_editor_suggestions() const { return Storage().isMember("editorSuggestions"); } /** * Clears the '<code>editorSuggestions</code>' attribute. */ void clear_editor_suggestions() { MutableStorage()->removeMember("editorSuggestions"); } /** * Get a reference to the value of the '<code>editorSuggestions</code>' * attribute. */ const client::JsonCppArray<string > get_editor_suggestions() const { const Json::Value& storage = Storage("editorSuggestions"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>editorSuggestions</code>' * property. * * A list of video editing operations that might improve the video quality or * playback experience of the uploaded video. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_editorSuggestions() { Json::Value* storage = MutableStorage("editorSuggestions"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>processingErrors</code>' attribute was set. * * @return true if the '<code>processingErrors</code>' attribute was set. */ bool has_processing_errors() const { return Storage().isMember("processingErrors"); } /** * Clears the '<code>processingErrors</code>' attribute. */ void clear_processing_errors() { MutableStorage()->removeMember("processingErrors"); } /** * Get a reference to the value of the '<code>processingErrors</code>' * attribute. */ const client::JsonCppArray<string > get_processing_errors() const { const Json::Value& storage = Storage("processingErrors"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>processingErrors</code>' * property. * * A list of errors that will prevent YouTube from successfully processing the * uploaded video video. These errors indicate that, regardless of the video's * current processing status, eventually, that status will almost certainly be * failed. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_processingErrors() { Json::Value* storage = MutableStorage("processingErrors"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>processingHints</code>' attribute was set. * * @return true if the '<code>processingHints</code>' attribute was set. */ bool has_processing_hints() const { return Storage().isMember("processingHints"); } /** * Clears the '<code>processingHints</code>' attribute. */ void clear_processing_hints() { MutableStorage()->removeMember("processingHints"); } /** * Get a reference to the value of the '<code>processingHints</code>' * attribute. */ const client::JsonCppArray<string > get_processing_hints() const { const Json::Value& storage = Storage("processingHints"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>processingHints</code>' * property. * * A list of suggestions that may improve YouTube's ability to process the * video. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_processingHints() { Json::Value* storage = MutableStorage("processingHints"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>processingWarnings</code>' attribute was set. * * @return true if the '<code>processingWarnings</code>' attribute was set. */ bool has_processing_warnings() const { return Storage().isMember("processingWarnings"); } /** * Clears the '<code>processingWarnings</code>' attribute. */ void clear_processing_warnings() { MutableStorage()->removeMember("processingWarnings"); } /** * Get a reference to the value of the '<code>processingWarnings</code>' * attribute. */ const client::JsonCppArray<string > get_processing_warnings() const { const Json::Value& storage = Storage("processingWarnings"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the * '<code>processingWarnings</code>' property. * * A list of reasons why YouTube may have difficulty transcoding the uploaded * video or that might result in an erroneous transcoding. These warnings are * generated before YouTube actually processes the uploaded video file. In * addition, they identify issues that are unlikely to cause the video * processing to fail but that might cause problems such as sync issues, video * artifacts, or a missing audio track. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_processingWarnings() { Json::Value* storage = MutableStorage("processingWarnings"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>tagSuggestions</code>' attribute was set. * * @return true if the '<code>tagSuggestions</code>' attribute was set. */ bool has_tag_suggestions() const { return Storage().isMember("tagSuggestions"); } /** * Clears the '<code>tagSuggestions</code>' attribute. */ void clear_tag_suggestions() { MutableStorage()->removeMember("tagSuggestions"); } /** * Get a reference to the value of the '<code>tagSuggestions</code>' * attribute. */ const client::JsonCppArray<VideoSuggestionsTagSuggestion > get_tag_suggestions() const; /** * Gets a reference to a mutable value of the '<code>tagSuggestions</code>' * property. * * A list of keyword tags that could be added to the video's metadata to * increase the likelihood that users will locate your video when searching or * browsing on YouTube. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<VideoSuggestionsTagSuggestion > mutable_tagSuggestions(); private: void operator=(const VideoSuggestions&); }; // VideoSuggestions } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_VIDEO_SUGGESTIONS_H_ <file_sep>/service_apis/youtube/google/youtube_api/comment_snippet.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_COMMENT_SNIPPET_H_ #define GOOGLE_YOUTUBE_API_COMMENT_SNIPPET_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Basic details about a comment, such as its author and text. * * @ingroup DataObject */ class CommentSnippet : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static CommentSnippet* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit CommentSnippet(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit CommentSnippet(Json::Value* storage); /** * Standard destructor. */ virtual ~CommentSnippet(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::CommentSnippet</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::CommentSnippet"); } /** * Determine if the '<code>authorChannelId</code>' attribute was set. * * @return true if the '<code>authorChannelId</code>' attribute was set. */ bool has_author_channel_id() const { return Storage().isMember("authorChannelId"); } /** * Clears the '<code>authorChannelId</code>' attribute. */ void clear_author_channel_id() { MutableStorage()->removeMember("authorChannelId"); } /** * Get a reference to the value of the '<code>authorChannelId</code>' * attribute. */ const client::JsonCppData get_author_channel_id() const { const Json::Value& storage = Storage("authorChannelId"); return client::JsonValueToCppValueHelper<client::JsonCppData >(storage); } /** * Gets a reference to a mutable value of the '<code>authorChannelId</code>' * property. * * The id of the author's YouTube channel, if any. * * @return The result can be modified to change the attribute value. */ client::JsonCppData mutable_authorChannelId() { Json::Value* storage = MutableStorage("authorChannelId"); return client::JsonValueToMutableCppValueHelper<client::JsonCppData >(storage); } /** * Determine if the '<code>authorChannelUrl</code>' attribute was set. * * @return true if the '<code>authorChannelUrl</code>' attribute was set. */ bool has_author_channel_url() const { return Storage().isMember("authorChannelUrl"); } /** * Clears the '<code>authorChannelUrl</code>' attribute. */ void clear_author_channel_url() { MutableStorage()->removeMember("authorChannelUrl"); } /** * Get the value of the '<code>authorChannelUrl</code>' attribute. */ const StringPiece get_author_channel_url() const { const Json::Value& v = Storage("authorChannelUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>authorChannelUrl</code>' attribute. * * Link to the author's YouTube channel, if any. * * @param[in] value The new value. */ void set_author_channel_url(const StringPiece& value) { *MutableStorage("authorChannelUrl") = value.data(); } /** * Determine if the '<code>authorDisplayName</code>' attribute was set. * * @return true if the '<code>authorDisplayName</code>' attribute was set. */ bool has_author_display_name() const { return Storage().isMember("authorDisplayName"); } /** * Clears the '<code>authorDisplayName</code>' attribute. */ void clear_author_display_name() { MutableStorage()->removeMember("authorDisplayName"); } /** * Get the value of the '<code>authorDisplayName</code>' attribute. */ const StringPiece get_author_display_name() const { const Json::Value& v = Storage("authorDisplayName"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>authorDisplayName</code>' attribute. * * The name of the user who posted the comment. * * @param[in] value The new value. */ void set_author_display_name(const StringPiece& value) { *MutableStorage("authorDisplayName") = value.data(); } /** * Determine if the '<code>authorProfileImageUrl</code>' attribute was set. * * @return true if the '<code>authorProfileImageUrl</code>' attribute was set. */ bool has_author_profile_image_url() const { return Storage().isMember("authorProfileImageUrl"); } /** * Clears the '<code>authorProfileImageUrl</code>' attribute. */ void clear_author_profile_image_url() { MutableStorage()->removeMember("authorProfileImageUrl"); } /** * Get the value of the '<code>authorProfileImageUrl</code>' attribute. */ const StringPiece get_author_profile_image_url() const { const Json::Value& v = Storage("authorProfileImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>authorProfileImageUrl</code>' attribute. * * The URL for the avatar of the user who posted the comment. * * @param[in] value The new value. */ void set_author_profile_image_url(const StringPiece& value) { *MutableStorage("authorProfileImageUrl") = value.data(); } /** * Determine if the '<code>canRate</code>' attribute was set. * * @return true if the '<code>canRate</code>' attribute was set. */ bool has_can_rate() const { return Storage().isMember("canRate"); } /** * Clears the '<code>canRate</code>' attribute. */ void clear_can_rate() { MutableStorage()->removeMember("canRate"); } /** * Get the value of the '<code>canRate</code>' attribute. */ bool get_can_rate() const { const Json::Value& storage = Storage("canRate"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canRate</code>' attribute. * * Whether the current viewer can rate this comment. * * @param[in] value The new value. */ void set_can_rate(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canRate")); } /** * Determine if the '<code>channelId</code>' attribute was set. * * @return true if the '<code>channelId</code>' attribute was set. */ bool has_channel_id() const { return Storage().isMember("channelId"); } /** * Clears the '<code>channelId</code>' attribute. */ void clear_channel_id() { MutableStorage()->removeMember("channelId"); } /** * Get the value of the '<code>channelId</code>' attribute. */ const StringPiece get_channel_id() const { const Json::Value& v = Storage("channelId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>channelId</code>' attribute. * * The id of the corresponding YouTube channel. In case of a channel comment * this is the channel the comment refers to. In case of a video comment it's * the video's channel. * * @param[in] value The new value. */ void set_channel_id(const StringPiece& value) { *MutableStorage("channelId") = value.data(); } /** * Determine if the '<code>likeCount</code>' attribute was set. * * @return true if the '<code>likeCount</code>' attribute was set. */ bool has_like_count() const { return Storage().isMember("likeCount"); } /** * Clears the '<code>likeCount</code>' attribute. */ void clear_like_count() { MutableStorage()->removeMember("likeCount"); } /** * Get the value of the '<code>likeCount</code>' attribute. */ uint32 get_like_count() const { const Json::Value& storage = Storage("likeCount"); return client::JsonValueToCppValueHelper<uint32 >(storage); } /** * Change the '<code>likeCount</code>' attribute. * * The total number of likes this comment has received. * * @param[in] value The new value. */ void set_like_count(uint32 value) { client::SetJsonValueFromCppValueHelper<uint32 >( value, MutableStorage("likeCount")); } /** * Determine if the '<code>moderationStatus</code>' attribute was set. * * @return true if the '<code>moderationStatus</code>' attribute was set. */ bool has_moderation_status() const { return Storage().isMember("moderationStatus"); } /** * Clears the '<code>moderationStatus</code>' attribute. */ void clear_moderation_status() { MutableStorage()->removeMember("moderationStatus"); } /** * Get the value of the '<code>moderationStatus</code>' attribute. */ const StringPiece get_moderation_status() const { const Json::Value& v = Storage("moderationStatus"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>moderationStatus</code>' attribute. * * The comment's moderation status. Will not be set if the comments were * requested through the id filter. * * @param[in] value The new value. */ void set_moderation_status(const StringPiece& value) { *MutableStorage("moderationStatus") = value.data(); } /** * Determine if the '<code>parentId</code>' attribute was set. * * @return true if the '<code>parentId</code>' attribute was set. */ bool has_parent_id() const { return Storage().isMember("parentId"); } /** * Clears the '<code>parentId</code>' attribute. */ void clear_parent_id() { MutableStorage()->removeMember("parentId"); } /** * Get the value of the '<code>parentId</code>' attribute. */ const StringPiece get_parent_id() const { const Json::Value& v = Storage("parentId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>parentId</code>' attribute. * * The unique id of the parent comment, only set for replies. * * @param[in] value The new value. */ void set_parent_id(const StringPiece& value) { *MutableStorage("parentId") = value.data(); } /** * Determine if the '<code>publishedAt</code>' attribute was set. * * @return true if the '<code>publishedAt</code>' attribute was set. */ bool has_published_at() const { return Storage().isMember("publishedAt"); } /** * Clears the '<code>publishedAt</code>' attribute. */ void clear_published_at() { MutableStorage()->removeMember("publishedAt"); } /** * Get the value of the '<code>publishedAt</code>' attribute. */ client::DateTime get_published_at() const { const Json::Value& storage = Storage("publishedAt"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>publishedAt</code>' attribute. * * The date and time when the comment was orignally published. The value is * specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. * * @param[in] value The new value. */ void set_published_at(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("publishedAt")); } /** * Determine if the '<code>textDisplay</code>' attribute was set. * * @return true if the '<code>textDisplay</code>' attribute was set. */ bool has_text_display() const { return Storage().isMember("textDisplay"); } /** * Clears the '<code>textDisplay</code>' attribute. */ void clear_text_display() { MutableStorage()->removeMember("textDisplay"); } /** * Get the value of the '<code>textDisplay</code>' attribute. */ const StringPiece get_text_display() const { const Json::Value& v = Storage("textDisplay"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>textDisplay</code>' attribute. * * The comment's text. The format is either plain text or HTML dependent on * what has been requested. Even the plain text representation may differ from * the text originally posted in that it may replace video links with video * titles etc. * * @param[in] value The new value. */ void set_text_display(const StringPiece& value) { *MutableStorage("textDisplay") = value.data(); } /** * Determine if the '<code>textOriginal</code>' attribute was set. * * @return true if the '<code>textOriginal</code>' attribute was set. */ bool has_text_original() const { return Storage().isMember("textOriginal"); } /** * Clears the '<code>textOriginal</code>' attribute. */ void clear_text_original() { MutableStorage()->removeMember("textOriginal"); } /** * Get the value of the '<code>textOriginal</code>' attribute. */ const StringPiece get_text_original() const { const Json::Value& v = Storage("textOriginal"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>textOriginal</code>' attribute. * * The comment's original raw text as initially posted or last updated. The * original text will only be returned if it is accessible to the viewer, * which is only guaranteed if the viewer is the comment's author. * * @param[in] value The new value. */ void set_text_original(const StringPiece& value) { *MutableStorage("textOriginal") = value.data(); } /** * Determine if the '<code>updatedAt</code>' attribute was set. * * @return true if the '<code>updatedAt</code>' attribute was set. */ bool has_updated_at() const { return Storage().isMember("updatedAt"); } /** * Clears the '<code>updatedAt</code>' attribute. */ void clear_updated_at() { MutableStorage()->removeMember("updatedAt"); } /** * Get the value of the '<code>updatedAt</code>' attribute. */ client::DateTime get_updated_at() const { const Json::Value& storage = Storage("updatedAt"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>updatedAt</code>' attribute. * * The date and time when was last updated . The value is specified in ISO * 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. * * @param[in] value The new value. */ void set_updated_at(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("updatedAt")); } /** * Determine if the '<code>videoId</code>' attribute was set. * * @return true if the '<code>videoId</code>' attribute was set. */ bool has_video_id() const { return Storage().isMember("videoId"); } /** * Clears the '<code>videoId</code>' attribute. */ void clear_video_id() { MutableStorage()->removeMember("videoId"); } /** * Get the value of the '<code>videoId</code>' attribute. */ const StringPiece get_video_id() const { const Json::Value& v = Storage("videoId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>videoId</code>' attribute. * * The ID of the video the comment refers to, if any. * * @param[in] value The new value. */ void set_video_id(const StringPiece& value) { *MutableStorage("videoId") = value.data(); } /** * Determine if the '<code>viewerRating</code>' attribute was set. * * @return true if the '<code>viewerRating</code>' attribute was set. */ bool has_viewer_rating() const { return Storage().isMember("viewerRating"); } /** * Clears the '<code>viewerRating</code>' attribute. */ void clear_viewer_rating() { MutableStorage()->removeMember("viewerRating"); } /** * Get the value of the '<code>viewerRating</code>' attribute. */ const StringPiece get_viewer_rating() const { const Json::Value& v = Storage("viewerRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>viewerRating</code>' attribute. * * The rating the viewer has given to this comment. For the time being this * will never return RATE_TYPE_DISLIKE and instead return RATE_TYPE_NONE. This * may change in the future. * * @param[in] value The new value. */ void set_viewer_rating(const StringPiece& value) { *MutableStorage("viewerRating") = value.data(); } private: void operator=(const CommentSnippet&); }; // CommentSnippet } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_COMMENT_SNIPPET_H_ <file_sep>/service_apis/youtube/google/youtube_api/channel_status.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_CHANNEL_STATUS_H_ #define GOOGLE_YOUTUBE_API_CHANNEL_STATUS_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * JSON template for the status part of a channel. * * @ingroup DataObject */ class ChannelStatus : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static ChannelStatus* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelStatus(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelStatus(Json::Value* storage); /** * Standard destructor. */ virtual ~ChannelStatus(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::ChannelStatus</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::ChannelStatus"); } /** * Determine if the '<code>isLinked</code>' attribute was set. * * @return true if the '<code>isLinked</code>' attribute was set. */ bool has_is_linked() const { return Storage().isMember("isLinked"); } /** * Clears the '<code>isLinked</code>' attribute. */ void clear_is_linked() { MutableStorage()->removeMember("isLinked"); } /** * Get the value of the '<code>isLinked</code>' attribute. */ bool get_is_linked() const { const Json::Value& storage = Storage("isLinked"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>isLinked</code>' attribute. * * If true, then the user is linked to either a YouTube username or G+ * account. Otherwise, the user doesn't have a public YouTube identity. * * @param[in] value The new value. */ void set_is_linked(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("isLinked")); } /** * Determine if the '<code>longUploadsStatus</code>' attribute was set. * * @return true if the '<code>longUploadsStatus</code>' attribute was set. */ bool has_long_uploads_status() const { return Storage().isMember("longUploadsStatus"); } /** * Clears the '<code>longUploadsStatus</code>' attribute. */ void clear_long_uploads_status() { MutableStorage()->removeMember("longUploadsStatus"); } /** * Get the value of the '<code>longUploadsStatus</code>' attribute. */ const StringPiece get_long_uploads_status() const { const Json::Value& v = Storage("longUploadsStatus"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>longUploadsStatus</code>' attribute. * * The long uploads status of this channel. See. * * @param[in] value The new value. */ void set_long_uploads_status(const StringPiece& value) { *MutableStorage("longUploadsStatus") = value.data(); } /** * Determine if the '<code>privacyStatus</code>' attribute was set. * * @return true if the '<code>privacyStatus</code>' attribute was set. */ bool has_privacy_status() const { return Storage().isMember("privacyStatus"); } /** * Clears the '<code>privacyStatus</code>' attribute. */ void clear_privacy_status() { MutableStorage()->removeMember("privacyStatus"); } /** * Get the value of the '<code>privacyStatus</code>' attribute. */ const StringPiece get_privacy_status() const { const Json::Value& v = Storage("privacyStatus"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>privacyStatus</code>' attribute. * * Privacy status of the channel. * * @param[in] value The new value. */ void set_privacy_status(const StringPiece& value) { *MutableStorage("privacyStatus") = value.data(); } private: void operator=(const ChannelStatus&); }; // ChannelStatus } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_CHANNEL_STATUS_H_ <file_sep>/service_apis/youtube/google/youtube_api/channel.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_CHANNEL_H_ #define GOOGLE_YOUTUBE_API_CHANNEL_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/channel_audit_details.h" #include "google/youtube_api/channel_branding_settings.h" #include "google/youtube_api/channel_content_details.h" #include "google/youtube_api/channel_content_owner_details.h" #include "google/youtube_api/channel_conversion_pings.h" #include "google/youtube_api/channel_localization.h" #include "google/youtube_api/channel_snippet.h" #include "google/youtube_api/channel_statistics.h" #include "google/youtube_api/channel_status.h" #include "google/youtube_api/channel_topic_details.h" #include "google/youtube_api/invideo_promotion.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * A channel resource contains information about a YouTube channel. * * @ingroup DataObject */ class Channel : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static Channel* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Channel(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Channel(Json::Value* storage); /** * Standard destructor. */ virtual ~Channel(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::Channel</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::Channel"); } /** * Determine if the '<code>auditDetails</code>' attribute was set. * * @return true if the '<code>auditDetails</code>' attribute was set. */ bool has_audit_details() const { return Storage().isMember("auditDetails"); } /** * Clears the '<code>auditDetails</code>' attribute. */ void clear_audit_details() { MutableStorage()->removeMember("auditDetails"); } /** * Get a reference to the value of the '<code>auditDetails</code>' attribute. */ const ChannelAuditDetails get_audit_details() const; /** * Gets a reference to a mutable value of the '<code>auditDetails</code>' * property. * * The auditionDetails object encapsulates channel data that is relevant for * YouTube Partners during the audition process. * * @return The result can be modified to change the attribute value. */ ChannelAuditDetails mutable_auditDetails(); /** * Determine if the '<code>brandingSettings</code>' attribute was set. * * @return true if the '<code>brandingSettings</code>' attribute was set. */ bool has_branding_settings() const { return Storage().isMember("brandingSettings"); } /** * Clears the '<code>brandingSettings</code>' attribute. */ void clear_branding_settings() { MutableStorage()->removeMember("brandingSettings"); } /** * Get a reference to the value of the '<code>brandingSettings</code>' * attribute. */ const ChannelBrandingSettings get_branding_settings() const; /** * Gets a reference to a mutable value of the '<code>brandingSettings</code>' * property. * * The brandingSettings object encapsulates information about the branding of * the channel. * * @return The result can be modified to change the attribute value. */ ChannelBrandingSettings mutable_brandingSettings(); /** * Determine if the '<code>contentDetails</code>' attribute was set. * * @return true if the '<code>contentDetails</code>' attribute was set. */ bool has_content_details() const { return Storage().isMember("contentDetails"); } /** * Clears the '<code>contentDetails</code>' attribute. */ void clear_content_details() { MutableStorage()->removeMember("contentDetails"); } /** * Get a reference to the value of the '<code>contentDetails</code>' * attribute. */ const ChannelContentDetails get_content_details() const; /** * Gets a reference to a mutable value of the '<code>contentDetails</code>' * property. * * The contentDetails object encapsulates information about the channel's * content. * * @return The result can be modified to change the attribute value. */ ChannelContentDetails mutable_contentDetails(); /** * Determine if the '<code>contentOwnerDetails</code>' attribute was set. * * @return true if the '<code>contentOwnerDetails</code>' attribute was set. */ bool has_content_owner_details() const { return Storage().isMember("contentOwnerDetails"); } /** * Clears the '<code>contentOwnerDetails</code>' attribute. */ void clear_content_owner_details() { MutableStorage()->removeMember("contentOwnerDetails"); } /** * Get a reference to the value of the '<code>contentOwnerDetails</code>' * attribute. */ const ChannelContentOwnerDetails get_content_owner_details() const; /** * Gets a reference to a mutable value of the * '<code>contentOwnerDetails</code>' property. * * The contentOwnerDetails object encapsulates channel data that is relevant * for YouTube Partners linked with the channel. * * @return The result can be modified to change the attribute value. */ ChannelContentOwnerDetails mutable_contentOwnerDetails(); /** * Determine if the '<code>conversionPings</code>' attribute was set. * * @return true if the '<code>conversionPings</code>' attribute was set. */ bool has_conversion_pings() const { return Storage().isMember("conversionPings"); } /** * Clears the '<code>conversionPings</code>' attribute. */ void clear_conversion_pings() { MutableStorage()->removeMember("conversionPings"); } /** * Get a reference to the value of the '<code>conversionPings</code>' * attribute. */ const ChannelConversionPings get_conversion_pings() const; /** * Gets a reference to a mutable value of the '<code>conversionPings</code>' * property. * * The conversionPings object encapsulates information about conversion pings * that need to be respected by the channel. * * @return The result can be modified to change the attribute value. */ ChannelConversionPings mutable_conversionPings(); /** * Determine if the '<code>etag</code>' attribute was set. * * @return true if the '<code>etag</code>' attribute was set. */ bool has_etag() const { return Storage().isMember("etag"); } /** * Clears the '<code>etag</code>' attribute. */ void clear_etag() { MutableStorage()->removeMember("etag"); } /** * Get the value of the '<code>etag</code>' attribute. */ const StringPiece get_etag() const { const Json::Value& v = Storage("etag"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>etag</code>' attribute. * * Etag of this resource. * * @param[in] value The new value. */ void set_etag(const StringPiece& value) { *MutableStorage("etag") = value.data(); } /** * Determine if the '<code>id</code>' attribute was set. * * @return true if the '<code>id</code>' attribute was set. */ bool has_id() const { return Storage().isMember("id"); } /** * Clears the '<code>id</code>' attribute. */ void clear_id() { MutableStorage()->removeMember("id"); } /** * Get the value of the '<code>id</code>' attribute. */ const StringPiece get_id() const { const Json::Value& v = Storage("id"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>id</code>' attribute. * * The ID that YouTube uses to uniquely identify the channel. * * @param[in] value The new value. */ void set_id(const StringPiece& value) { *MutableStorage("id") = value.data(); } /** * Determine if the '<code>invideoPromotion</code>' attribute was set. * * @return true if the '<code>invideoPromotion</code>' attribute was set. */ bool has_invideo_promotion() const { return Storage().isMember("invideoPromotion"); } /** * Clears the '<code>invideoPromotion</code>' attribute. */ void clear_invideo_promotion() { MutableStorage()->removeMember("invideoPromotion"); } /** * Get a reference to the value of the '<code>invideoPromotion</code>' * attribute. */ const InvideoPromotion get_invideo_promotion() const; /** * Gets a reference to a mutable value of the '<code>invideoPromotion</code>' * property. * * The invideoPromotion object encapsulates information about promotion * campaign associated with the channel. * * @return The result can be modified to change the attribute value. */ InvideoPromotion mutable_invideoPromotion(); /** * Determine if the '<code>kind</code>' attribute was set. * * @return true if the '<code>kind</code>' attribute was set. */ bool has_kind() const { return Storage().isMember("kind"); } /** * Clears the '<code>kind</code>' attribute. */ void clear_kind() { MutableStorage()->removeMember("kind"); } /** * Get the value of the '<code>kind</code>' attribute. */ const StringPiece get_kind() const { const Json::Value& v = Storage("kind"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kind</code>' attribute. * * Identifies what kind of resource this is. Value: the fixed string * "youtube#channel". * * @param[in] value The new value. */ void set_kind(const StringPiece& value) { *MutableStorage("kind") = value.data(); } /** * Determine if the '<code>localizations</code>' attribute was set. * * @return true if the '<code>localizations</code>' attribute was set. */ bool has_localizations() const { return Storage().isMember("localizations"); } /** * Clears the '<code>localizations</code>' attribute. */ void clear_localizations() { MutableStorage()->removeMember("localizations"); } /** * Get a reference to the value of the '<code>localizations</code>' attribute. */ const client::JsonCppAssociativeArray<ChannelLocalization > get_localizations() const; /** * Gets a reference to a mutable value of the '<code>localizations</code>' * property. * * Localizations for different languages. * * @return The result can be modified to change the attribute value. */ client::JsonCppAssociativeArray<ChannelLocalization > mutable_localizations(); /** * Determine if the '<code>snippet</code>' attribute was set. * * @return true if the '<code>snippet</code>' attribute was set. */ bool has_snippet() const { return Storage().isMember("snippet"); } /** * Clears the '<code>snippet</code>' attribute. */ void clear_snippet() { MutableStorage()->removeMember("snippet"); } /** * Get a reference to the value of the '<code>snippet</code>' attribute. */ const ChannelSnippet get_snippet() const; /** * Gets a reference to a mutable value of the '<code>snippet</code>' property. * * The snippet object contains basic details about the channel, such as its * title, description, and thumbnail images. * * @return The result can be modified to change the attribute value. */ ChannelSnippet mutable_snippet(); /** * Determine if the '<code>statistics</code>' attribute was set. * * @return true if the '<code>statistics</code>' attribute was set. */ bool has_statistics() const { return Storage().isMember("statistics"); } /** * Clears the '<code>statistics</code>' attribute. */ void clear_statistics() { MutableStorage()->removeMember("statistics"); } /** * Get a reference to the value of the '<code>statistics</code>' attribute. */ const ChannelStatistics get_statistics() const; /** * Gets a reference to a mutable value of the '<code>statistics</code>' * property. * * The statistics object encapsulates statistics for the channel. * * @return The result can be modified to change the attribute value. */ ChannelStatistics mutable_statistics(); /** * Determine if the '<code>status</code>' attribute was set. * * @return true if the '<code>status</code>' attribute was set. */ bool has_status() const { return Storage().isMember("status"); } /** * Clears the '<code>status</code>' attribute. */ void clear_status() { MutableStorage()->removeMember("status"); } /** * Get a reference to the value of the '<code>status</code>' attribute. */ const ChannelStatus get_status() const; /** * Gets a reference to a mutable value of the '<code>status</code>' property. * * The status object encapsulates information about the privacy status of the * channel. * * @return The result can be modified to change the attribute value. */ ChannelStatus mutable_status(); /** * Determine if the '<code>topicDetails</code>' attribute was set. * * @return true if the '<code>topicDetails</code>' attribute was set. */ bool has_topic_details() const { return Storage().isMember("topicDetails"); } /** * Clears the '<code>topicDetails</code>' attribute. */ void clear_topic_details() { MutableStorage()->removeMember("topicDetails"); } /** * Get a reference to the value of the '<code>topicDetails</code>' attribute. */ const ChannelTopicDetails get_topic_details() const; /** * Gets a reference to a mutable value of the '<code>topicDetails</code>' * property. * * The topicDetails object encapsulates information about Freebase topics * associated with the channel. * * @return The result can be modified to change the attribute value. */ ChannelTopicDetails mutable_topicDetails(); private: void operator=(const Channel&); }; // Channel } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_CHANNEL_H_ <file_sep>/src/samples/command_processor.h /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ // // Command Processor class provides a basic shell interpreter for writing apps. // It might be useful for writing experimental code that makes API calls. // I use it in some samples. #ifndef GOOGLEAPIS_SAMPLES_COMMAND_PROCESSOR_H_ #define GOOGLEAPIS_SAMPLES_COMMAND_PROCESSOR_H_ #include <map> #include <memory> #include <string> using std::string; #include <utility> #include <vector> #include "googleapis/base/callback.h" #include "googleapis/base/macros.h" #include "googleapis/client/transport/http_response.h" namespace googleapis { namespace sample { using client::HttpResponse; class CommandProcessor { public: CommandProcessor(); virtual ~CommandProcessor(); // Controller for the application takes input commands, runs them, and // prints the output/errors to the console. virtual void RunShell(); void set_prompt(const string& prompt) { prompt_ = prompt; } const string& prompt() const { return prompt_; } // If true then CheckAndLogResponse will also log the http_response.body() // for messages that are http_response.ok() void set_log_success_bodies(bool on) { log_success_bodies_ = on; } bool log_success_bodies() const { return log_success_bodies_; } // Split args into list separating by spaces unless they are escaped // or within quotes. // Returns true if args were ok. False if they ended prematurely. // Even if false is returned, the list will contain the best interpretation // of the args. static bool SplitArgs(const string& phrase, std::vector<string>* list); protected: typedef Callback2<const string&, const std::vector<string>&> CommandRunner; struct CommandEntry { CommandEntry( const string& usage_args, const string& description, CommandRunner* callback) : args(usage_args), help(description), runner(callback) { callback->CheckIsRepeatable(); } static bool CompareEntry( const std::pair<const string, const CommandEntry*>& a, const std::pair<const string, const CommandEntry*>& b) { return a.first < b.first; } const string args; const string help; std::unique_ptr<CommandRunner> runner; private: DISALLOW_COPY_AND_ASSIGN(CommandEntry); }; // Sets up command processor with available commands. // Derived classes should override this and call AddCommand with their // various commands. // // The base method adds the builtin commands (calls AddBulitinCommands) virtual void InitCommands(); void AddCommand(string name, CommandEntry* details); // For displaying errors, etc. bool CheckAndLogResponse(HttpResponse* response); // Handler for "quit" command. virtual void QuitHandler(const string&, const std::vector<string>&); // Handler for "help" command. virtual void HelpHandler(const string&, const std::vector<string>&); // Handler for "quiet" and "verbose" commands. virtual void VerboseHandler(int level, const string&, const std::vector<string>&); // Adds builtin 'help' and 'quit' commands. // Called by InitCommands but offered separately so you dont need to // propagate InitCommands when overriding it. void AddBuiltinCommands(); private: // maps command name to entry map for exeuting it. typedef std::map<string, CommandEntry*> CommandEntryMap; CommandEntryMap commands_; string prompt_; bool log_success_bodies_; bool done_; DISALLOW_COPY_AND_ASSIGN(CommandProcessor); }; } // namespace sample } // namespace googleapis #endif // GOOGLEAPIS_SAMPLES_COMMAND_PROCESSOR_H_ <file_sep>/service_apis/drive/google/drive_api/property.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Drive API (drive/v2) // Generated from: // Version: v2 // Revision: 20170512 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_DRIVE_API_PROPERTY_H_ #define GOOGLE_DRIVE_API_PROPERTY_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_drive_api { using namespace googleapis; /** * A key-value pair attached to a file that is either public or private to an * application. * The following limits apply to file properties: * - Maximum of 100 properties total per file * - Maximum of 30 private properties per app * - Maximum of 30 public properties * - Maximum of 124 bytes size limit on (key + value) string in UTF-8 encoding * for a single property. * * @ingroup DataObject */ class Property : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static Property* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Property(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Property(Json::Value* storage); /** * Standard destructor. */ virtual ~Property(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::Property</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::Property"); } /** * Determine if the '<code>etag</code>' attribute was set. * * @return true if the '<code>etag</code>' attribute was set. */ bool has_etag() const { return Storage().isMember("etag"); } /** * Clears the '<code>etag</code>' attribute. */ void clear_etag() { MutableStorage()->removeMember("etag"); } /** * Get the value of the '<code>etag</code>' attribute. */ const StringPiece get_etag() const { const Json::Value& v = Storage("etag"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>etag</code>' attribute. * * ETag of the property. * * @param[in] value The new value. */ void set_etag(const StringPiece& value) { *MutableStorage("etag") = value.data(); } /** * Determine if the '<code>key</code>' attribute was set. * * @return true if the '<code>key</code>' attribute was set. */ bool has_key() const { return Storage().isMember("key"); } /** * Clears the '<code>key</code>' attribute. */ void clear_key() { MutableStorage()->removeMember("key"); } /** * Get the value of the '<code>key</code>' attribute. */ const StringPiece get_key() const { const Json::Value& v = Storage("key"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>key</code>' attribute. * * The key of this property. * * @param[in] value The new value. */ void set_key(const StringPiece& value) { *MutableStorage("key") = value.data(); } /** * Determine if the '<code>kind</code>' attribute was set. * * @return true if the '<code>kind</code>' attribute was set. */ bool has_kind() const { return Storage().isMember("kind"); } /** * Clears the '<code>kind</code>' attribute. */ void clear_kind() { MutableStorage()->removeMember("kind"); } /** * Get the value of the '<code>kind</code>' attribute. */ const StringPiece get_kind() const { const Json::Value& v = Storage("kind"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kind</code>' attribute. * * This is always drive#property. * * @param[in] value The new value. */ void set_kind(const StringPiece& value) { *MutableStorage("kind") = value.data(); } /** * Determine if the '<code>selfLink</code>' attribute was set. * * @return true if the '<code>selfLink</code>' attribute was set. */ bool has_self_link() const { return Storage().isMember("selfLink"); } /** * Clears the '<code>selfLink</code>' attribute. */ void clear_self_link() { MutableStorage()->removeMember("selfLink"); } /** * Get the value of the '<code>selfLink</code>' attribute. */ const StringPiece get_self_link() const { const Json::Value& v = Storage("selfLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>selfLink</code>' attribute. * * The link back to this property. * * @param[in] value The new value. */ void set_self_link(const StringPiece& value) { *MutableStorage("selfLink") = value.data(); } /** * Determine if the '<code>value</code>' attribute was set. * * @return true if the '<code>value</code>' attribute was set. */ bool has_value() const { return Storage().isMember("value"); } /** * Clears the '<code>value</code>' attribute. */ void clear_value() { MutableStorage()->removeMember("value"); } /** * Get the value of the '<code>value</code>' attribute. */ const StringPiece get_value() const { const Json::Value& v = Storage("value"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>value</code>' attribute. * * The value of this property. * * @param[in] value The new value. */ void set_value(const StringPiece& value) { *MutableStorage("value") = value.data(); } /** * Determine if the '<code>visibility</code>' attribute was set. * * @return true if the '<code>visibility</code>' attribute was set. */ bool has_visibility() const { return Storage().isMember("visibility"); } /** * Clears the '<code>visibility</code>' attribute. */ void clear_visibility() { MutableStorage()->removeMember("visibility"); } /** * Get the value of the '<code>visibility</code>' attribute. */ const StringPiece get_visibility() const { const Json::Value& v = Storage("visibility"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>visibility</code>' attribute. * * The visibility of this property. * * @param[in] value The new value. */ void set_visibility(const StringPiece& value) { *MutableStorage("visibility") = value.data(); } private: void operator=(const Property&); }; // Property } // namespace google_drive_api #endif // GOOGLE_DRIVE_API_PROPERTY_H_ <file_sep>/service_apis/youtube/google/youtube_api/playlist.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Description: // Supports core YouTube features, such as uploading videos, creating and managing playlists, searching for content, and much more. // Classes: // Playlist // Documentation: // https://developers.google.com/youtube/v3 #include "google/youtube_api/playlist.h" #include <string> #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/playlist_content_details.h" #include "google/youtube_api/playlist_localization.h" #include "google/youtube_api/playlist_player.h" #include "google/youtube_api/playlist_snippet.h" #include "google/youtube_api/playlist_status.h" #include <string> #include "googleapis/strings/strcat.h" namespace google_youtube_api { using namespace googleapis; // Object factory method (static). Playlist* Playlist::New() { return new client::JsonCppCapsule<Playlist>; } // Standard immutable constructor. Playlist::Playlist(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. Playlist::Playlist(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. Playlist::~Playlist() { } // Properties. const PlaylistContentDetails Playlist::get_content_details() const { const Json::Value& storage = Storage("contentDetails"); return client::JsonValueToCppValueHelper<PlaylistContentDetails >(storage); } PlaylistContentDetails Playlist::mutable_contentDetails() { Json::Value* storage = MutableStorage("contentDetails"); return client::JsonValueToMutableCppValueHelper<PlaylistContentDetails >(storage); } const client::JsonCppAssociativeArray<PlaylistLocalization > Playlist::get_localizations() const { const Json::Value& storage = Storage("localizations"); return client::JsonValueToCppValueHelper<client::JsonCppAssociativeArray<PlaylistLocalization > >(storage); } client::JsonCppAssociativeArray<PlaylistLocalization > Playlist::mutable_localizations() { Json::Value* storage = MutableStorage("localizations"); return client::JsonValueToMutableCppValueHelper<client::JsonCppAssociativeArray<PlaylistLocalization > >(storage); } const PlaylistPlayer Playlist::get_player() const { const Json::Value& storage = Storage("player"); return client::JsonValueToCppValueHelper<PlaylistPlayer >(storage); } PlaylistPlayer Playlist::mutable_player() { Json::Value* storage = MutableStorage("player"); return client::JsonValueToMutableCppValueHelper<PlaylistPlayer >(storage); } const PlaylistSnippet Playlist::get_snippet() const { const Json::Value& storage = Storage("snippet"); return client::JsonValueToCppValueHelper<PlaylistSnippet >(storage); } PlaylistSnippet Playlist::mutable_snippet() { Json::Value* storage = MutableStorage("snippet"); return client::JsonValueToMutableCppValueHelper<PlaylistSnippet >(storage); } const PlaylistStatus Playlist::get_status() const { const Json::Value& storage = Storage("status"); return client::JsonValueToCppValueHelper<PlaylistStatus >(storage); } PlaylistStatus Playlist::mutable_status() { Json::Value* storage = MutableStorage("status"); return client::JsonValueToMutableCppValueHelper<PlaylistStatus >(storage); } } // namespace google_youtube_api <file_sep>/src/googleapis/client/CMakeLists.txt # NOTE: cmake -D CURL_STATICLIB=string:ON to build curl library with static lib project (GoogleApis_C++_Client) # just for testing include_directories(${CMAKE_CURRENT_SOURCE_DIR}/test) include_directories(${GFLAGS_INCLUDES} ${GTEST_INCLUDES}) configure_file(data/roots.pem ${EXECUTABLE_OUTPUT_PATH}/roots.pem COPYONLY) # Abstract JSON support independent of underlying implementation. # Libraries should use this where possible so actual implementation libraries # are decoupled. This potentially allows different service libraries to have # different json implementations for their data objects in the same binary. add_library(googleapis_json STATIC data/serializable_json.cc) target_link_libraries(googleapis_json googleapis_utils) target_link_libraries(googleapis_json googleapis_internal) install(TARGETS googleapis_json DESTINATION ${GOOGLEAPIS_INSTALL_LIB_DIR}) install(FILES data/serializable_json.h DESTINATION ${GOOGLEAPIS_INSTALL_INCLUDE_DIR}/client/data) # Generic utility functions supporting the core googleapis components. # This will combine the Data Layer and utility/programing support. # since there isnt a pragmatic reason to separate their runtime packaging. add_library(googleapis_utils STATIC data/base64_codec.cc data/codec.cc data/data_reader.cc data/data_writer.cc data/composite_data_reader.cc data/file_data_reader.cc data/inmemory_data_reader.cc data/istream_data_reader.cc util/date_time.cc util/escaping.cc util/file_utils.cc util/program_path.cc util/status.cc util/uri_template.cc util/uri_utils.cc) target_link_libraries(googleapis_utils ${GLOG_LIBRARY}) target_link_libraries(googleapis_utils googleapis_internal) install(TARGETS googleapis_utils DESTINATION ${GOOGLEAPIS_INSTALL_LIB_DIR}) install(FILES data/codec.h data/base64_codec.h data/data_reader.h data/data_writer.h DESTINATION ${GOOGLEAPIS_INSTALL_INCLUDE_DIR}/client/data) install(FILES util/date_time.h util/escaping.h util/file_utils.h util/program_path.h util/status.h util/uri_template.h util/uri_utils.h DESTINATION ${GOOGLEAPIS_INSTALL_INCLUDE_DIR}/client/util) if (HAVE_MONGOOSE) add_library(googleapis_mongoose STATIC util/abstract_webserver.cc util/mongoose_webserver.cc auth/webserver_authorization_getter.cc) target_link_libraries(googleapis_mongoose googleapis_oauth2) target_link_libraries(googleapis_mongoose googleapis_utils) target_link_libraries(googleapis_mongoose ${GLOG_LIBRARY}) target_link_libraries(googleapis_mongoose mongoose) if (MSVC) else() target_link_libraries(googleapis_mongoose dl) # for mongoose endif() install(TARGETS googleapis_mongoose DESTINATION ${GOOGLEAPIS_INSTALL_LIB_DIR}) install(FILES util/mongoose_webserver.h DESTINATION ${GOOGLEAPIS_INSTALL_INCLUDE_DIR}/client/util) endif (HAVE_MONGOOSE) install(FILES auth/oauth2_pending_authorizations.h DESTINATION ${GOOGLEAPIS_INSTALL_INCLUDE_DIR}/client/auth) # A concrete JSON implementation using JsonCpp (external package). add_library(googleapis_jsoncpp STATIC data/jsoncpp_data.cc) target_link_libraries(googleapis_jsoncpp googleapis_json) target_link_libraries(googleapis_jsoncpp googleapis_utils) target_link_libraries(googleapis_jsoncpp jsoncpp) target_link_libraries(googleapis_jsoncpp googleapis_internal) install(TARGETS googleapis_jsoncpp DESTINATION ${GOOGLEAPIS_INSTALL_LIB_DIR}) install(FILES data/jsoncpp_data.h data/jsoncpp_data_helpers.h DESTINATION ${GOOGLEAPIS_INSTALL_INCLUDE_DIR}/client/data) # The TransportLayer and ClientServiceLayer components of the # googleapis libraries. This also includes generic Authorization components # but not OAuth 2.0 specific components. add_library(googleapis_http STATIC auth/credential_store.cc auth/file_credential_store.cc transport/ca_paths.cc transport/http_authorization.cc transport/http_request.cc transport/http_request_batch.cc transport/http_response.cc transport/http_scribe.cc transport/http_transport.cc transport/http_transport_global_state.cc transport/versioninfo.cc service/client_service.cc service/media_uploader.cc service/service_request_pager.cc) target_link_libraries(googleapis_http ${GLOG_LIBRARY}) target_link_libraries(googleapis_http googleapis_utils) target_link_libraries(googleapis_http googleapis_internal) install(TARGETS googleapis_http DESTINATION ${GOOGLEAPIS_INSTALL_LIB_DIR}) install(FILES auth/credential_store.h auth/file_credential_store.h DESTINATION ${GOOGLEAPIS_INSTALL_INCLUDE_DIR}/client/auth) install(FILES transport/http_authorization.h transport/http_request.h transport/http_request_batch.h transport/http_response.h transport/http_scribe.h transport/http_transport.h transport/http_types.h transport/versioninfo.h DESTINATION ${GOOGLEAPIS_INSTALL_INCLUDE_DIR}/client/transport) install(FILES service/client_service.h service/media_uploader.h service/service_request_pager.h DESTINATION ${GOOGLEAPIS_INSTALL_INCLUDE_DIR}/client/service) # Concrete scribe implementations. add_library(googleapis_scribes STATIC transport/html_scribe.cc transport/json_scribe.cc) target_link_libraries(googleapis_scribes googleapis_utils) target_link_libraries(googleapis_scribes googleapis_internal) install(TARGETS googleapis_scribes DESTINATION ${GOOGLEAPIS_INSTALL_LIB_DIR}) install(FILES transport/html_scribe.h transport/json_scribe.h DESTINATION ${GOOGLEAPIS_INSTALL_INCLUDE_DIR}/client/transport) add_library(googleapis_jsonplayback STATIC transport/json_playback_transport.cc) target_link_libraries(googleapis_jsonplayback googleapis_http) target_link_libraries(googleapis_jsonplayback googleapis_scribes) target_link_libraries(googleapis_jsonplayback googleapis_utils) target_link_libraries(googleapis_jsonplayback googleapis_internal) target_link_libraries(googleapis_jsonplayback jsoncpp) install(TARGETS googleapis_jsonplayback DESTINATION ${GOOGLEAPIS_INSTALL_LIB_DIR}) install(FILES transport/json_playback_transport.h DESTINATION ${GOOGLEAPIS_INSTALL_INCLUDE_DIR}/client) # Implementation of OAuth2 add_library(googleapis_oauth2 STATIC auth/oauth2_authorization.cc) target_link_libraries(googleapis_oauth2 ${GLOG_LIBRARY}) target_link_libraries(googleapis_oauth2 googleapis_http) target_link_libraries(googleapis_oauth2 googleapis_internal) target_link_libraries(googleapis_oauth2 jsoncpp) install(TARGETS googleapis_oauth2 DESTINATION ${GOOGLEAPIS_INSTALL_LIB_DIR}) install(FILES auth/oauth2_authorization.h DESTINATION ${GOOGLEAPIS_INSTALL_INCLUDE_DIR}/client/auth) if (HAVE_OPENSSL) # Concrete Codec implementation using OpenSSL (external package). add_library(googleapis_openssl_codec STATIC data/openssl_codec.cc) target_link_libraries(googleapis_openssl_codec crypto) target_link_libraries(googleapis_openssl_codec dl) # For crypto target_link_libraries(googleapis_openssl_codec googleapis_internal) target_link_libraries(googleapis_openssl_codec googleapis_utils) install(TARGETS googleapis_openssl_codec DESTINATION ${GOOGLEAPIS_INSTALL_LIB_DIR}) install(FILES data/openssl_codec.h DESTINATION ${GOOGLEAPIS_INSTALL_INCLUDE_DIR}/client/data) endif() # Concrete HttpTransport implementation using Curl (external package). add_library(googleapis_curl_http STATIC transport/curl_http_transport.cc) target_link_libraries(googleapis_curl_http ${CURL_LIBRARY}) target_link_libraries(googleapis_curl_http ${GLOG_LIBRARY}) target_link_libraries(googleapis_curl_http googleapis_http) target_link_libraries(googleapis_curl_http googleapis_internal) if (HAVE_OPENSSL) target_link_libraries(googleapis_curl_http ssl) target_link_libraries(googleapis_curl_http crypto) target_link_libraries(googleapis_curl_http dl) endif() install(TARGETS googleapis_curl_http DESTINATION ${GOOGLEAPIS_INSTALL_LIB_DIR}) install(FILES transport/curl_http_transport.h DESTINATION ${GOOGLEAPIS_INSTALL_INCLUDE_DIR}/client/transport) if (googleapis_build_tests) add_library(googleapis_http_transport_test_fixture STATIC transport/test/http_transport_test_fixture.cc) target_link_libraries(googleapis_http_transport_test_fixture googleapis_json) target_link_libraries(googleapis_http_transport_test_fixture googleapis_jsoncpp) target_link_libraries(googleapis_http_transport_test_fixture googleapis_http) target_link_libraries(googleapis_http_transport_test_fixture googleapis_scribes) target_link_libraries(googleapis_http_transport_test_fixture googleapis_internal) target_link_libraries(googleapis_http_transport_test_fixture ${GLOG_LIBRARY}) target_link_libraries(googleapis_http_transport_test_fixture ${GFLAGS_LIBRARY}) target_link_libraries(googleapis_http_transport_test_fixture gtest) # Some gtest enhancements to facilitate test setup and cleanup. add_library(googleapis_gtest_main STATIC util/test/googleapis_gtest_main.cc) target_link_libraries(googleapis_gtest_main googleapis_internal) target_link_libraries(googleapis_gtest_main ${GLOG_LIBRARY}) target_link_libraries(googleapis_gtest_main gtest_main) endif (googleapis_build_tests) # Defines an executable and adds a test for it using the most basic libraries # Args: # name - name of test. Must have a source file in test/<name>.cc # ... - optional list of additional library dependencies function(client_test module name) add_executable(${name} ${module}/test/${name}.cc) foreach (lib "${ARGN}") target_link_libraries(${name} ${lib}) endforeach() target_link_libraries(${name} googleapis_internal) target_link_libraries(${name} ${GLOG_LIBRARY}) target_link_libraries(${name} gmock) target_link_libraries(${name} googleapis_gtest_main) add_test(${name} ${EXECUTABLE_OUTPUT_PATH}/${name}) endfunction() # Defines an executable and adds a test for it using the standard googleapis # libraries. # # Args: # name - name of test. Must have a source file in test/<name>.cc # ... - optional list of additional library dependencies function(googleapis_test module name) client_test(${module} ${name} googleapis_json googleapis_http googleapis_utils ${ARGN}) endfunction() if (googleapis_build_tests) client_test(util date_time_test googleapis_utils) client_test(util file_utils_test googleapis_utils) client_test(util uri_template_test googleapis_utils) client_test(util uri_utils_test googleapis_utils) client_test(data jsoncpp_data_test googleapis_jsoncpp) client_test(data base64_codec_test googleapis_utils) client_test(data composite_data_reader_test googleapis_utils) client_test(data data_reader_test googleapis_utils) # TODO(user): Fix test client_test(data data_writer_test googleapis_utils) client_test(data file_data_reader_test googleapis_utils) client_test(data inmemory_data_reader_test googleapis_utils) client_test(data istream_data_reader_test googleapis_utils) if (HAVE_OPENSSL) client_test(data openssl_codec_test googleapis_utils googleapis_openssl_codec) endif() googleapis_test(auth oauth2_authorization_test googleapis_oauth2) # TODO(user): Fix test googleapis_test(auth file_credential_store_test) googleapis_test(transport http_request_batch_test) googleapis_test(transport http_scribe_test) googleapis_test(transport html_scribe_test googleapis_scribes) googleapis_test(transport http_transport_test) googleapis_test(transport curl_http_transport_test googleapis_http_transport_test_fixture googleapis_curl_http) googleapis_test(transport json_playback_transport_test googleapis_http_transport_test_fixture googleapis_jsonplayback) # The data file within the test is specified relative to the base build tree. SET_TESTS_PROPERTIES(json_playback_transport_test PROPERTIES WORKING_DIRECTORY ${CMAKE_BINARY_DIR}) googleapis_test(service client_service_test) googleapis_test(service media_uploader_test) googleapis_test(service service_request_pager_test) # This is a test but dont treat it as one because it isnt automated. add_executable(interactive_oauth2_authorization_test auth/test/interactive_oauth2_authorization_test.cc) target_link_libraries(interactive_oauth2_authorization_test googleapis_json) target_link_libraries(interactive_oauth2_authorization_test googleapis_http) target_link_libraries(interactive_oauth2_authorization_test googleapis_internal) target_link_libraries(interactive_oauth2_authorization_test googleapis_curl_http) if (HAVE_MONGOOSE) target_link_libraries(interactive_oauth2_authorization_test googleapis_mongoose) endif (HAVE_MONGOOSE) target_link_libraries(interactive_oauth2_authorization_test googleapis_internal) target_link_libraries(interactive_oauth2_authorization_test googleapis_gtest_main) target_link_libraries(interactive_oauth2_authorization_test ${GLOG_LIBRARY}) target_link_libraries(interactive_oauth2_authorization_test ${GFLAGS_LIBRARY}) endif() # googleapis_build_tests <file_sep>/src/samples/gdriveutil_main.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ // // Note that in this example we often IgnoreError when Executing. // This is because we look at the status in the response and detect errors // there. Checking the result of Execute would be redundant. The IgnoreError // calls are just to explicitly acknowledge the googleapis::util::Status returned by // Execute. // // If we were automatically destroying the request then it would not be // valid when Execute() returns and would need to use the googleapis::util::Status // returned by Execute in order to check for errors. #include <iostream> using std::cout; using std::endl; using std::ostream; // NOLINT #include <memory> #include <string> using std::string; #include <vector> #include "samples/command_processor.h" #include "samples/installed_application.h" #include "googleapis/client/data/data_reader.h" #include "googleapis/client/data/data_writer.h" #include "googleapis/client/data/file_data_writer.h" #include "googleapis/client/transport/curl_http_transport.h" #include "googleapis/client/transport/http_request.h" #include "googleapis/client/transport/http_response.h" #include "googleapis/client/service/media_uploader.h" #include "google/drive_api/drive_api.h" #include <gflags/gflags.h> #include "googleapis/base/macros.h" #include "googleapis/base/callback.h" #include <glog/logging.h> #include "googleapis/util/file.h" #include "googleapis/strings/strcat.h" namespace googleapis { DEFINE_int32(max_results, 5, "Max results for listing files."); DEFINE_string(client_secrets_path, "", "REQUIRED: Path to JSON client_secrets file for OAuth."); DEFINE_int32(port, 0, "If specified, use this port with an httpd for OAuth 2.0"); using std::cin; using std::cerr; using std::cout; using std::endl; using client::HttpTransport; using client::HttpRequest; using client::HttpResponse; using client::JsonCppArray; // only because we arent using C++x11 using client::JsonCppAssociativeArray; // because not using C++x11 using client::ClientService; using client::DataReader; using client::NewUnmanagedFileDataReader; using client::StatusOk; using client::StatusUnknown; using google_drive_api::DriveService; using google_drive_api::AboutResource_GetMethod; using google_drive_api::FilesResource_DeleteMethod; using google_drive_api::FilesResource_GetMethod; using google_drive_api::FilesResource_InsertMethod; using google_drive_api::FilesResource_ListMethod; using google_drive_api::FilesResource_ListMethodPager; using google_drive_api::FilesResource_TrashMethod; using google_drive_api::FilesResource_UpdateMethod; using google_drive_api::RevisionsResource_GetMethod; using google_drive_api::RevisionsResource_ListMethod; using sample::InstalledServiceApplication; using sample::CommandProcessor; /** * Example of a writer which could provide download progress. */ class ProgressMeterDataWriter : public client::FileDataWriter { public: explicit ProgressMeterDataWriter(const string& path) : client::FileDataWriter(path, FileOpenOptions()) { } ~ProgressMeterDataWriter() override { cout << "~ProgressMeterDataWriter" << endl; } googleapis::util::Status DoWrite(int64 bytes, const char* buffer) override { // In a real application, we might callback to the UI to display here. cout << "*** Got another " << bytes << " bytes." << endl; return client::FileDataWriter::DoWrite(bytes, buffer); } std::unique_ptr<client::DataWriter> file_writer_; }; class DriveUtilApplication : public InstalledServiceApplication<DriveService> { public: DriveUtilApplication() : InstalledServiceApplication<DriveService>("GDriveUtil") { std::vector<string>* scopes = mutable_default_oauth2_scopes(); scopes->push_back(DriveService::SCOPES::DRIVE_READONLY); scopes->push_back(DriveService::SCOPES::DRIVE_FILE); scopes->push_back(DriveService::SCOPES::DRIVE); // Not adding metadata scope because I dont think I'm using // anything needing it } protected: virtual googleapis::util::Status InitServiceHelper() { if (FLAGS_port > 0) { client::WebServerAuthorizationCodeGetter::AskCallback* asker = NewPermanentCallback( &client::WebServerAuthorizationCodeGetter ::PromptWithCommand, "/usr/bin/firefox", "\"$URL\""); // "/opt/google/chrome/google-chrome", "--app=\"$URL\""); return StartupHttpd(FLAGS_port, "/oauth", asker); } return StatusOk(); } private: DISALLOW_COPY_AND_ASSIGN(DriveUtilApplication); }; class DriveCommandProcessor : public sample::CommandProcessor { public: explicit DriveCommandProcessor(DriveUtilApplication* app) : app_(app) {} virtual ~DriveCommandProcessor() {} virtual void Init() { AddBuiltinCommands(); AddCommand("authorize", new CommandEntry( "user_name [refresh token]", "Re-authorize user [with refresh token].\n" "The user_name is only used for persisting the credentials.\n" "The credentials will be persisted under the directory " "$HOME/.googleapis/user_name.\n" "If refresh token is empty then authorize interactively.", NewPermanentCallback( this, &DriveCommandProcessor::AuthorizeHandler))); AddCommand("revoke", new CommandEntry( "", "Revoke authorization. You will need to reauthorize again.\n", NewPermanentCallback( this, &DriveCommandProcessor::RevokeHandler))); AddCommand("about", new CommandEntry( "", "Get information about yourself and drive settings.", NewPermanentCallback(this, &DriveCommandProcessor::AboutHandler))); AddCommand("list", new CommandEntry( "", "List your files. Can page through using 'next'.", NewPermanentCallback( this, &DriveCommandProcessor::ListFilesHandler))); AddCommand("next", new CommandEntry( "", "List the next page since the previous 'list' or 'next'.", NewPermanentCallback( this, &DriveCommandProcessor::NextFilesHandler))); AddCommand("revisions", new CommandEntry( "<fileid>", "List the revisions for the given fileid.", NewPermanentCallback( this, &DriveCommandProcessor::FileRevisionsHandler))); AddCommand("upload", new CommandEntry( "<path> [<mime-type>]", "Upload the path to your GDrive. If no mime-type is given then it" " is assumed to be text/plain", NewPermanentCallback( this, &DriveCommandProcessor::UploadFileHandler))); AddCommand("delete", new CommandEntry( "<fileid>", "Delete the given fileid", NewPermanentCallback( this, &DriveCommandProcessor::DeleteFileHandler))); AddCommand("trash", new CommandEntry( "<fileid>", "Permanently delete the given fileid", NewPermanentCallback( this, &DriveCommandProcessor::TrashFileHandler))); AddCommand("update", new CommandEntry( "<fileid> <path> [<mime-type>]", "Update the fileid with the contents of the given path", NewPermanentCallback( this, &DriveCommandProcessor::UpdateFileHandler))); AddCommand("download", new CommandEntry( "<fileid> <path|-> [<mime_type>] [<revisionid>]", "Download the specified fileid." " If a mime_type is provided, download that version." " If a revision is supplied then download that particular one." " Otherwise download whatever is on the GDrive.", NewPermanentCallback( this, &DriveCommandProcessor::DownloadRevisionHandler))); } private: void AboutHandler(const string&, const std::vector<string>&) { const DriveService::AboutResource& rsrc = app_->service()->get_about(); std::unique_ptr<AboutResource_GetMethod> get( rsrc.NewGetMethod(app_->credential())); cout << "Finding out about you..." << endl; std::unique_ptr<google_drive_api::About> about( google_drive_api::About::New()); get->ExecuteAndParseResponse(about.get()).IgnoreError(); if (CheckAndLogResponse(get->http_response())) { cout << " Name: " << about->get_name(); } } void AuthorizeHandler(const string& cmd, const std::vector<string>& args) { if (args.size() == 0 || args.size() > 2) { cout << "no user_name provided." << endl; return; } googleapis::util::Status status = app_->ChangeUser(args[0]); if (status.ok()) { status = app_->AuthorizeClient(); } if (status.ok()) { cout << "Authorized as user '" << args[0] << "'" << endl; } else { cerr << status.ToString(); } } void RevokeHandler(const string&, const std::vector<string>&) { app_->RevokeClient().IgnoreError(); } void ShowFiles(const google_drive_api::FileList& list) { const JsonCppArray<google_drive_api::File>& items = list.get_items(); if (items.size() == 0) { cout << "No files." << endl; return; } // We can use C++11 style iterators here, i.e. // for (google_drive_api::File file : list.get_items()) // But for the sake of broader compilers we'll be traditional. const char* sep = ""; for ( JsonCppArray<google_drive_api::File>::const_iterator it = items.begin(); it != items.end(); ++it) { const google_drive_api::File& file = *it; cout << sep; if (file.get_labels().get_trashed()) { cout << "*** TRASHED *** "; // continue ID on this line } else if (file.get_labels().get_hidden()) { cout << "*** HIDDEN *** "; // continue ID on this line } cout << "ID: " << file.get_id() << endl; cout << " Size: " << file.get_file_size() << endl; cout << " MimeType: " << file.get_mime_type() << endl; cout << " Created: " << file.get_created_date().ToString() << endl; cout << " Description: " << file.get_description() << endl; cout << " Download Url: " << file.get_download_url() << endl; cout << " Original Name: " << file.get_original_filename() << endl; cout << " Modified By: " << file.get_last_modifying_user_name() << endl; sep = "\n"; } } void ListFilesHandler(const string&, const std::vector<string>&) { const DriveService::FilesResource& rsrc = app_->service()->get_files(); // We could use a FilesResource_ListMethod but we'll instead use // a pager so that we can play with it. Reset the old one (if any). // The 'next' command will advance the pager. list_pager_.reset(rsrc.NewListMethodPager(app_->credential())); list_pager_->request()->set_max_results(FLAGS_max_results); cout << "Getting (partial) file list..." << endl; bool ok = list_pager_->NextPage(); CheckAndLogResponse(list_pager_->http_response()); if (ok) { ShowFiles(*list_pager_->data()); } if (list_pager_->is_done()) { cout << "There are no more results to page through." << endl; } else { cout << "\nEnter 'next' to see the next page of results." << endl; } } void NextFilesHandler(const string&, const std::vector<string>&) { if (!list_pager_.get()) { cout << "Cannot page through files util you 'list' them." << endl; return; } cout << "Getting next page of file list..." << endl; bool ok = list_pager_->NextPage(); CheckAndLogResponse(list_pager_->http_response()); if (ok) { ShowFiles(*list_pager_->data()); } if (list_pager_->is_done()) { cout << "There are no more results to page through." << endl; } else { cout << "\nEnter 'next' to see the next page of results." << endl; } } void UploadFileHandler(const string& cmd, const std::vector<string>& args) { if (args.size() < 1 || args.size() > 2) { cout << "Usage: " << cmd << " <path> [<mime-type>]" << endl; return; } const string& path = args[0]; const string& mime_type = args.size() > 1 ? args[1] : "text/plain"; std::unique_ptr<google_drive_api::File> file(google_drive_api::File::New()); file->set_title(StrCat("Uploaded from ", file::Basename(path))); file->set_editable(true); file->set_original_filename(file::Basename(path)); DataReader* reader = NewUnmanagedFileDataReader(path); cout << "Uploading "<< reader->TotalLengthIfKnown() << " bytes from type=" << mime_type << " path=" << path << endl; const DriveService::FilesResource& rsrc = app_->service()->get_files(); std::unique_ptr<FilesResource_InsertMethod> insert( rsrc.NewInsertMethod( app_->credential(), file.get(), mime_type, reader)); insert->set_convert(false); insert->Execute().IgnoreError(); CheckAndLogResponse(insert->http_response()); } void UpdateFileHandler(const string& cmd, const std::vector<string>& args) { if (args.size() < 2 || args.size() > 3) { cout << "Usage: " << cmd << " <fileid> <path> [<mime-type>]" << endl; return; } const string& fileid = args[0]; const string& path = args[1]; const string& mime_type = args.size() > 2 ? args[2] : "text/plain"; DataReader* reader = NewUnmanagedFileDataReader(path); cout << "Updating fileid=" << fileid << " with " << reader->TotalLengthIfKnown() << " bytes from type=" << mime_type << " path=" << path << endl; const DriveService::FilesResource& rsrc = app_->service()->get_files(); std::unique_ptr<google_drive_api::File> file(google_drive_api::File::New()); file->set_title(StrCat("Updated from ", file::Basename(path))); file->set_original_filename(file::Basename(path)); std::unique_ptr<FilesResource_UpdateMethod> update( rsrc.NewUpdateMethod( app_->credential(), fileid, file.get(), mime_type, reader)); update->Execute().IgnoreError(); CheckAndLogResponse(update->http_response()); } void DeleteFileHandler(const string& cmd, const std::vector<string>& args) { if (args.size() < 1) { cout << "Usage: " << cmd << " <fileid>" << endl; return; } const string& fileid = args[0]; const DriveService::FilesResource& rsrc = app_->service()->get_files(); std::unique_ptr<FilesResource_DeleteMethod> remove( rsrc.NewDeleteMethod(app_->credential(), fileid)); cout << "Deleting fileid=" << fileid << "..." << endl; remove->Execute().IgnoreError(); CheckAndLogResponse(remove->http_response()); } void TrashFileHandler(const string& cmd, const std::vector<string>& args) { if (args.size() < 1) { cout << "Usage: " << cmd << " <fileid>" << endl; return; } const string& fileid = args[0]; const DriveService::FilesResource& rsrc = app_->service()->get_files(); std::unique_ptr<FilesResource_TrashMethod> trash( rsrc.NewTrashMethod(app_->credential(), fileid)); cout << "Trashing fileid=" << fileid << "..." << endl; trash->Execute().IgnoreError(); CheckAndLogResponse(trash->http_response()); } void FileRevisionsHandler(const string& cmd, const std::vector<string>& args) { if (args.size() < 1) { cout << "Usage: " << cmd << " <fileid>" << endl; return; } const string& fileid = args[0]; const DriveService::RevisionsResource& rsrc = app_->service()->get_revisions(); std::unique_ptr<RevisionsResource_ListMethod> list( rsrc.NewListMethod(app_->credential(), fileid)); cout << "Getting evisions for " << fileid << "..." << endl; std::unique_ptr<google_drive_api::RevisionList> revision_list( google_drive_api::RevisionList::New()); list->ExecuteAndParseResponse(revision_list.get()).IgnoreError(); if (CheckAndLogResponse(list->http_response())) { const JsonCppArray<google_drive_api::Revision> all_items = revision_list->get_items(); for (JsonCppArray<google_drive_api::Revision>::const_iterator it = all_items.begin(); it != all_items.end(); ++it) { const google_drive_api::Revision& revision = *it; cout << "ID: " << revision.get_id() << endl; cout << " FileSize: " << revision.get_file_size() << endl; cout << " Modified on " << revision.get_modified_date().ToString() << " by " << revision.get_last_modifying_user_name() << endl; if (revision.get_published()) { cout << " Published URL: " << revision.get_published_link() << endl; } cout << " Export Links:" << endl; const JsonCppAssociativeArray<string>& export_links = revision.get_export_links(); for (JsonCppAssociativeArray<string>::const_iterator it = export_links.begin(); it != export_links.end(); ++it) { cout << " " << it.key() << ": " << it.value() << endl; } } } } void DownloadRevisionHandler(const string& cmd, const std::vector<string>& args) { if ((args.size() < 2) || args.size() > 4) { cout << "Usage: " << cmd << " <fileid> <path|->" << "[<mime-type>] [<revisionid>]" << endl; return; } string url; const string kNone; const string& fileid = args[0]; const string& path = args[1]; const string& mime_type = args.size() > 2 ? args[2] : kNone; const string& revisionid = args.size() > 3 ? args[3] : kNone; std::unique_ptr<client::JsonCppData> client_response; if (revisionid.empty()) { const DriveService::FilesResource& rsrc = app_->service()->get_files(); std::unique_ptr<FilesResource_GetMethod> get( rsrc.NewGetMethod(app_->credential(), fileid)); std::unique_ptr<google_drive_api::File> file( google_drive_api::File::New()); cout << "Downloading file_id=" << fileid << endl; get->ExecuteAndParseResponse(file.get()).IgnoreError(); if (!CheckAndLogResponse(get->http_response())) { return; } client_response.reset(file.release()); } else { const DriveService::RevisionsResource& rsrc = app_->service()->get_revisions(); std::unique_ptr<RevisionsResource_GetMethod> get( rsrc.NewGetMethod(app_->credential(), fileid, revisionid)); std::unique_ptr<google_drive_api::Revision> revision(google_drive_api::Revision::New()); cout << "Downloading revision " << revisionid << " of file_id" << fileid << endl; get->ExecuteAndParseResponse(revision.get()).IgnoreError(); if (!CheckAndLogResponse(get->http_response())) { return; } client_response.reset(revision.release()); } if (!mime_type.empty()) { const Json::Value& storage = client_response->Storage("exportLinks"); url = storage[mime_type.c_str()].asString(); if (url.empty()) { cout << "*** No mime_type=" << mime_type << " available for download."; return; } } else { url = client_response->Storage("downloadUrl").asString(); if (url.empty()) { cout << "Drive gives no downloadUrl so you must give a mime type."; return; } } std::unique_ptr<HttpRequest> request( app_->service()->transport()->NewHttpRequest(HttpRequest::GET)); request->set_url(url); request->set_credential(app_->credential()); bool to_file = path != "-"; if (to_file) { client::DataWriter* writer = new ProgressMeterDataWriter(path); request->set_content_writer(writer); } request->Execute().IgnoreError(); HttpResponse* download_response = request->response(); if (download_response->ok()) { if (to_file) { cout << "*** Downloaded to: " << path << endl; } else { string body; googleapis::util::Status status = download_response->GetBodyString(&body); cout << "*** Here's what I downloaded:" << endl; cout << body << endl; } } else { cout << download_response->status().error_message() << endl; } } std::unique_ptr<FilesResource_ListMethodPager> list_pager_; DriveUtilApplication* app_; DISALLOW_COPY_AND_ASSIGN(DriveCommandProcessor); }; } // namespace googleapis using namespace googleapis; int main(int argc, char* argv[]) { google::ParseCommandLineFlags(&argc, &argv, true); if (FLAGS_client_secrets_path.empty()) { LOG(ERROR) << "--client_secrets_path not set"; return -1; } DriveUtilApplication app; googleapis::util::Status status = app.Init(FLAGS_client_secrets_path); if (!status.ok()) { LOG(ERROR) << "Could not initialize application: " << status.error_message() << endl;; return -1; } DriveCommandProcessor processor(&app); processor.Init(); processor.set_log_success_bodies(true); processor.RunShell(); return 0; } <file_sep>/src/samples/abstract_webserver_login_flow.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <string> using std::string; #include "samples/abstract_webserver_login_flow.h" #include "googleapis/client/auth/oauth2_authorization.h" #include "googleapis/client/auth/oauth2_pending_authorizations.h" #include "googleapis/client/transport/http_request.h" #include "googleapis/client/transport/http_types.h" #include "googleapis/client/util/status.h" #include "googleapis/base/callback.h" #include <glog/logging.h> #include "googleapis/strings/strcat.h" #include "googleapis/util/hash.h" namespace googleapis { using client::WebServerRequest; using client::OAuth2AuthorizationFlow; using client::OAuth2PendingAuthorizations; using client::OAuth2RequestOptions; using client::OAuth2Credential; using client::ParsedUrl; using client::StatusUnknown; namespace sample { AbstractWebServerLoginFlow::AbstractWebServerLoginFlow( const string& cookie_name, const string& redirect_name, OAuth2AuthorizationFlow* flow) : AbstractLoginFlow(cookie_name, redirect_name, flow) { pending_.reset(new OAuth2PendingAuthorizations<PendingAuthorizationHandler>); } AbstractWebServerLoginFlow::~AbstractWebServerLoginFlow() { } util::Status AbstractWebServerLoginFlow::DoInitiateAuthorizationFlow( WebServerRequest* request, const string& redirect_url) { string cookie_id = GetCookieId(request); string want_url; if (redirect_url.empty()) { want_url = request->parsed_url().url(); } else { want_url = redirect_url; } VLOG(1) << "No credential for cookie=" << cookie_id << " so save " << want_url << " while we ask"; OAuth2RequestOptions options; string authorize_url = flow()->GenerateAuthorizationCodeRequestUrlWithOptions(options); int key = pending_->AddAuthorizationCodeHandler( NewCallback(this, &AbstractWebServerLoginFlow::ReceiveAuthorizationCode, cookie_id, want_url)); authorize_url.append("&state=%x"); char tmp[50]; snprintf(tmp, sizeof(tmp), "%x", key); authorize_url.append(tmp); VLOG(1) << "Redirecting cookie=" << cookie_id << " to authorize"; return RedirectToUrl(authorize_url, cookie_id, request); } util::Status AbstractWebServerLoginFlow::ReceiveAuthorizationCode( const string& cookie_id, const string& want_url, WebServerRequest* request) { string error; string code; const ParsedUrl& parsed_url = request->parsed_url(); bool have_code = parsed_url.GetQueryParameter("code", &code); bool have_error = parsed_url.GetQueryParameter("error", &error); googleapis::util::Status status; if (have_error) { status = StatusUnknown(StrCat("Did not authorize: ", error)); } else if (!have_code) { status = StatusUnknown("Missing authorization code"); } OAuth2Credential* new_credential = NULL; if (status.ok()) { LOG(INFO) << "Received AuthorizationCode for cookie=" << cookie_id; OAuth2RequestOptions options; std::unique_ptr<OAuth2Credential> credential(flow()->NewCredential()); status = flow()->PerformExchangeAuthorizationCode( code, options, credential.get()); if (status.ok()) { LOG(INFO) << "Got credential for cookie=" << cookie_id; new_credential = credential.release(); } else { LOG(INFO) << "Failed to get credential for cookie=" << cookie_id; } } DoReceiveCredentialForCookieId(cookie_id, status, new_credential); if (!want_url.empty()) { LOG(INFO) << "Restoring continuation for cookie=" << cookie_id; if (status.ok()) { return RedirectToUrl(want_url, cookie_id, request); } else { return DoRespondWithLoginErrorPage(cookie_id, status, request); } } else { return DoRespondWithWelcomePage(cookie_id, request); } } // This callback is used to resolve the requests from the OAuth 2.0 server // that gives us the authentication codes (or responses) that we asked for. util::Status AbstractWebServerLoginFlow::DoHandleAccessTokenUrl( WebServerRequest* request) { string state; request->parsed_url().GetQueryParameter("state", &state); int32 key; bool valid = safe_strto32_base(state, &key, 16); PendingAuthorizationHandler* handler = valid ? pending_->FindAndRemoveHandlerForKey(key) : NULL; if (handler == NULL) { LOG(INFO) << "Got unexpected authorization code"; string result_body = StrCat("Unexpected state=", state); return request->response()->SendReply( client::HttpRequest::ContentType_TEXT, client::HttpStatusCode::NOT_FOUND, result_body); } return handler->Run(request); } } // namespace sample } // namespace googleapis <file_sep>/src/samples/abstract_gplus_login_flow.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ // // This implementation is generally based on // https://developers.google.com/+/web/signin/#using_the_client-side_flow // // If we had a templating engine then we should use it here. // However for the time being I'm trying to keep dependencies down. // Since this is not yet part of the core library, I'm not introducing // a templating engine for it. Instead I tried to use a simple variable // substitution to make the templated strings more readable, then perform // string substitution on the variables. #include <string> using std::string; #include "samples/abstract_gplus_login_flow.h" #include "googleapis/client/auth/oauth2_authorization.h" #include "googleapis/client/transport/http_types.h" #include "googleapis/client/util/abstract_webserver.h" #include "googleapis/client/util/status.h" #include "googleapis/strings/strcat.h" #include "googleapis/strings/util.h" namespace googleapis { using client::AbstractWebServer; using client::HttpStatusCode; using client::OAuth2AuthorizationFlow; using client::OAuth2Credential; using client::ParsedUrl; using client::StatusUnknown; using client::WebServerRequest; using client::WebServerResponse; namespace sample { AbstractGplusLoginFlow::AbstractGplusLoginFlow( const string& cookie_name, const string& redirect_name, OAuth2AuthorizationFlow* flow) : AbstractLoginFlow(cookie_name, redirect_name, flow) { } AbstractGplusLoginFlow::~AbstractGplusLoginFlow() {} // This is pretty much from Step 2 on: // https://developers.google.com/+/web/signin/#using_the_client-side_flow string AbstractGplusLoginFlow::GetPrerequisiteHeadHtml() { const string kFetchScript = "<script type='text/javascript'>\n" "(function() {\n" " var po = document.createElement('script');\n" " po.type = 'text/javascript'; po.async = false;\n" // !!! " po.src = 'https://apis.google.com/js/client:plusone.js';\n" " var s = document.getElementsByTagName('script')[0];\n" " s.parentNode.insertBefore(po, s);\n" "})();\n" "</script>\n"; return kFetchScript; } // This is pretty much from Step 3 on: // https://developers.google.com/+/web/signin/#using_the_client-side_flow // // This is different in that the button is invisible by default. // We're also going to make sure the renderer was configured correctly. // If the renderer is not configured correctly it will render errors instead // of the button. string AbstractGplusLoginFlow::GetSigninButtonHtml(bool default_visible) { string error; if (access_token_url().empty()) { error.append("<li>Did not AddPokeUrl."); } if (client_id_.empty()) { error.append("<li>Missing 'client_id' config."); } if (!error.empty()) { return StrCat("<ol>", error, "</ol>"); } string html = StrCat( "<span id='signinButton'$VISIBLE>" "<span" " class='g-signin'" " data-callback='signinCallback'" " data-clientid='", client_id_, "'" " data-cookiepolicy='single_host_origin'" " data-requestvisibleactions=''" " data-scope='", scopes_, "'>" "</span>" "</span>"); string style = default_visible ? "" : " style='display:none'"; return StringReplace(html, "$VISIBLE", style, false); } // This is based on Step 4 from: // https://developers.google.com/+/web/signin/#using_the_client-side_flow // // When we get a login we're going to poke the data into the server. // We're going to use an additional state parameter so the server can // correlate the credential with the user since the poke is an unsolicited // HTTP GET call. // // On success we'll execute the success_block parameter after setting the // credential so it can redirect. // On failure we'll execute the failure block. // // Success an failure will make the button visible and hidden. string AbstractGplusLoginFlow::GetSigninCallbackJavascriptHtml( const string& state, const string& immediate_block, const string& success_block, const string& failure_block) { string javascript_template = "<script type='text/javascript'>\n" "function signinCallback(authResult) {\n" " if (authResult['access_token']) {\n" " document.getElementById('signinButton')" ".setAttribute('style', 'display:none');\n" " var url = '$POKE_URL'\n" " + '?state=$STATE'\n" " + '&access_token=' + authResult['access_token']\n" " + '&id_token=' + authResult['id_token'];\n" "$MAYBE_LOG_ACCESS_TOKEN_AND_GET_URL" " var xmlHttp = new XMLHttpRequest();\n" " xmlHttp.open('GET', url, false);\n" " xmlHttp.send(null);\n" "$MAYBE_LOG_GOT_URL" " if (xmlHttp.responseText == 'LOGIN') {\n" " document.location.reload(true);\n" " }\n" "$SUCCESS_BLOCK" " }\n" " else if (authResult['error']) {\n" "$MAYBE_LOG_ERROR" " if (authResult['error'] == 'immediate_failed') {\n" "$IMMEDIATE_FAILURE" " } else {\n" "$FAILURE_BLOCK" " }\n" " document.getElementById('signinButton')" ".setAttribute('style', 'display:inline');\n" " }\n" "}\n" "</script>\n"; string html = javascript_template; if (!immediate_block.empty()) { const string reload_javascript = " var url = '$POKE_URL'\n" " + '?state=$STATE'\n" " + '&access_token=' + authResult['access_token']\n" " + '&id_token=' + authResult['id_token'];\n" "$MAYBE_LOG_CLEAR_ACCESS_TOKEN_AND_GET_URL" " var xmlHttp = new XMLHttpRequest();\n" " xmlHttp.open('GET', url, false);\n" " xmlHttp.send(null);\n" "$MAYBE_LOG_GOT_URL" " if (xmlHttp.responseText == 'LOGIN') {\n" " document.location.reload(true);\n" " }\n"; html = StringReplace(html, "$IMMEDIATE_FAILURE", reload_javascript, false); } else { html = StringReplace(html, "$IMMEDIATE_FAILURE", "", false); } html = StringReplace(html, "$POKE_URL", access_token_url(), true); html = StringReplace(html, "$STATE", state, true); if (success_block.empty()) { html = StringReplace(html, "$SUCCESS_BLOCK", "", false); } else { html = StringReplace( html, "$SUCCESS_BLOCK", StrCat(" ", success_block), false); } if (failure_block.empty()) { html = StringReplace(html, "$FAILURE_BLOCK", "", false); } else { html = StringReplace( html, "$FAILURE_BLOCK", StrCat(" var error = authResult['error'];\n", " ", failure_block, ";\n"), false); } if (log_to_console_) { html = StringReplace( html, "$MAYBE_LOG_ACCESS_TOKEN_AND_GET_URL", " console.log('GOT Access Token');\n" " console.log('GET ' + url);\n", false); html = StringReplace( html, "$MAYBE_LOG_CLEAR_ACCESS_TOKEN_AND_GET_URL", " console.log('CLEAR Access Token');\n" " console.log('GET ' + url);\n", false); html = StringReplace( html, "$MAYBE_LOG_ERROR", " console.log('Signin Error: ' + authResult['error']);\n", false); html = StringReplace( html, "$MAYBE_LOG_GOT_URL", " console.log('GOT ' + xmlHttp.status " "+ ' ' + xmlHttp.responseText);\n", true); } else { html = StringReplace(html, "$MAYBE_LOG_ACCESS_TOKEN_AND_GET_URL", "", false); html = StringReplace(html, "$MAYBE_LOG_CLEAR_ACCESS_TOKEN_AND_GET_URL", "", false); html = StringReplace(html, "$MAYBE_LOG_ERROR", "", false); html = StringReplace(html, "$MAYBE_LOG_GOT_URL", "", true); } return html; } util::Status AbstractGplusLoginFlow::DoInitiateAuthorizationFlow( WebServerRequest* request, const string& redirect_url) { return DoRespondWithNotLoggedInPage(GetCookieId(request), request); } // It is specific to our local user repository. util::Status AbstractGplusLoginFlow::DoHandleAccessTokenUrl( WebServerRequest* request) { VLOG(1) << "Poke url handlerr=" << request->parsed_url().url(); int http_code; string msg; string access_token; string cookie_id; const ParsedUrl& parsed_url = request->parsed_url(); if (!parsed_url.GetQueryParameter("access_token", &access_token)) { http_code = HttpStatusCode::BAD_REQUEST; msg = "No access_token provided"; } else if (!parsed_url.GetQueryParameter("state", &cookie_id) || cookie_id.empty()) { http_code = HttpStatusCode::BAD_REQUEST; msg = "No state param"; } else if (access_token.empty()) { http_code = HttpStatusCode::OK; msg = "Revoked permissions"; DoReceiveCredentialForCookieId( cookie_id, client::StatusOk(), NULL); } else { OAuth2Credential* credential = flow()->NewCredential(); credential->set_access_token(access_token); googleapis::util::Status status; if (!DoReceiveCredentialForCookieId( cookie_id, client::StatusOk(), credential)) { msg = "LOGIN"; } else { msg = "Welcome back."; } http_code = 200; } return request->response()->SendText(http_code, msg); } } // namespace sample } // namespace googleapis <file_sep>/service_apis/youtube/google/youtube_api/thumbnail_details.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_THUMBNAIL_DETAILS_H_ #define GOOGLE_YOUTUBE_API_THUMBNAIL_DETAILS_H_ #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/thumbnail.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Internal representation of thumbnails for a YouTube resource. * * @ingroup DataObject */ class ThumbnailDetails : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static ThumbnailDetails* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ThumbnailDetails(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ThumbnailDetails(Json::Value* storage); /** * Standard destructor. */ virtual ~ThumbnailDetails(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::ThumbnailDetails</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::ThumbnailDetails"); } /** * Determine if the '<code>default</code>' attribute was set. * * @return true if the '<code>default</code>' attribute was set. */ bool has_default() const { return Storage().isMember("default"); } /** * Clears the '<code>default</code>' attribute. */ void clear_default() { MutableStorage()->removeMember("default"); } /** * Get a reference to the value of the '<code>default</code>' attribute. */ const Thumbnail get_default() const; /** * Gets a reference to a mutable value of the '<code>default</code>' property. * * The default image for this resource. * * @return The result can be modified to change the attribute value. */ Thumbnail mutable_default(); /** * Determine if the '<code>high</code>' attribute was set. * * @return true if the '<code>high</code>' attribute was set. */ bool has_high() const { return Storage().isMember("high"); } /** * Clears the '<code>high</code>' attribute. */ void clear_high() { MutableStorage()->removeMember("high"); } /** * Get a reference to the value of the '<code>high</code>' attribute. */ const Thumbnail get_high() const; /** * Gets a reference to a mutable value of the '<code>high</code>' property. * * The high quality image for this resource. * * @return The result can be modified to change the attribute value. */ Thumbnail mutable_high(); /** * Determine if the '<code>maxres</code>' attribute was set. * * @return true if the '<code>maxres</code>' attribute was set. */ bool has_maxres() const { return Storage().isMember("maxres"); } /** * Clears the '<code>maxres</code>' attribute. */ void clear_maxres() { MutableStorage()->removeMember("maxres"); } /** * Get a reference to the value of the '<code>maxres</code>' attribute. */ const Thumbnail get_maxres() const; /** * Gets a reference to a mutable value of the '<code>maxres</code>' property. * * The maximum resolution quality image for this resource. * * @return The result can be modified to change the attribute value. */ Thumbnail mutable_maxres(); /** * Determine if the '<code>medium</code>' attribute was set. * * @return true if the '<code>medium</code>' attribute was set. */ bool has_medium() const { return Storage().isMember("medium"); } /** * Clears the '<code>medium</code>' attribute. */ void clear_medium() { MutableStorage()->removeMember("medium"); } /** * Get a reference to the value of the '<code>medium</code>' attribute. */ const Thumbnail get_medium() const; /** * Gets a reference to a mutable value of the '<code>medium</code>' property. * * The medium quality image for this resource. * * @return The result can be modified to change the attribute value. */ Thumbnail mutable_medium(); /** * Determine if the '<code>standard</code>' attribute was set. * * @return true if the '<code>standard</code>' attribute was set. */ bool has_standard() const { return Storage().isMember("standard"); } /** * Clears the '<code>standard</code>' attribute. */ void clear_standard() { MutableStorage()->removeMember("standard"); } /** * Get a reference to the value of the '<code>standard</code>' attribute. */ const Thumbnail get_standard() const; /** * Gets a reference to a mutable value of the '<code>standard</code>' * property. * * The standard quality image for this resource. * * @return The result can be modified to change the attribute value. */ Thumbnail mutable_standard(); private: void operator=(const ThumbnailDetails&); }; // ThumbnailDetails } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_THUMBNAIL_DETAILS_H_ <file_sep>/service_apis/youtube/google/youtube_api/you_tube_service.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // //------------------------------------------------------------------------------ // This code was generated by google-apis-code-generator 1.5.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. //------------------------------------------------------------------------------ #include "google/youtube_api/you_tube_service.h" #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/client/service/client_service.h" #include "googleapis/client/service/media_uploader.h" #include "googleapis/client/service/service_request_pager.h" #include "googleapis/client/util/date_time.h" #include "googleapis/client/util/status.h" #include "google/youtube_api/activity.h" #include "google/youtube_api/activity_list_response.h" #include "google/youtube_api/caption.h" #include "google/youtube_api/caption_list_response.h" #include "google/youtube_api/channel.h" #include "google/youtube_api/channel_banner_resource.h" #include "google/youtube_api/channel_list_response.h" #include "google/youtube_api/channel_section.h" #include "google/youtube_api/channel_section_list_response.h" #include "google/youtube_api/comment.h" #include "google/youtube_api/comment_list_response.h" #include "google/youtube_api/comment_thread.h" #include "google/youtube_api/comment_thread_list_response.h" #include "google/youtube_api/fan_funding_event_list_response.h" #include "google/youtube_api/guide_category_list_response.h" #include "google/youtube_api/i18n_language_list_response.h" #include "google/youtube_api/i18n_region_list_response.h" #include "google/youtube_api/invideo_branding.h" #include "google/youtube_api/live_broadcast.h" #include "google/youtube_api/live_broadcast_list_response.h" #include "google/youtube_api/live_chat_ban.h" #include "google/youtube_api/live_chat_message.h" #include "google/youtube_api/live_chat_message_list_response.h" #include "google/youtube_api/live_chat_moderator.h" #include "google/youtube_api/live_chat_moderator_list_response.h" #include "google/youtube_api/live_stream.h" #include "google/youtube_api/live_stream_list_response.h" #include "google/youtube_api/playlist.h" #include "google/youtube_api/playlist_item.h" #include "google/youtube_api/playlist_item_list_response.h" #include "google/youtube_api/playlist_list_response.h" #include "google/youtube_api/search_list_response.h" #include "google/youtube_api/sponsor_list_response.h" #include "google/youtube_api/subscription.h" #include "google/youtube_api/subscription_list_response.h" #include "google/youtube_api/super_chat_event_list_response.h" #include "google/youtube_api/thumbnail_set_response.h" #include "google/youtube_api/video.h" #include "google/youtube_api/video_abuse_report.h" #include "google/youtube_api/video_abuse_report_reason_list_response.h" #include "google/youtube_api/video_category_list_response.h" #include "google/youtube_api/video_get_rating_response.h" #include "google/youtube_api/video_list_response.h" #include "googleapis/client/data/data_reader.h" #include "googleapis/client/transport/http_request.h" #include "googleapis/client/transport/http_transport.h" #include "googleapis/client/util/uri_utils.h" #include "googleapis/strings/strcat.h" namespace google_youtube_api { using namespace googleapis; const char YouTubeService::googleapis_API_NAME[] = {"youtube"}; const char YouTubeService::googleapis_API_VERSION[] = {"v3"}; const char YouTubeService::googleapis_API_GENERATOR[] = { "google-apis-code-generator 1.5.1 / 0.1.4"}; const char YouTubeService::SCOPES::YOUTUBE[] = {"https://www.googleapis.com/auth/youtube"}; const char YouTubeService::SCOPES::YOUTUBE_FORCE_SSL[] = {"https://www.googleapis.com/auth/youtube.force-ssl"}; const char YouTubeService::SCOPES::YOUTUBE_READONLY[] = {"https://www.googleapis.com/auth/youtube.readonly"}; const char YouTubeService::SCOPES::YOUTUBE_UPLOAD[] = {"https://www.googleapis.com/auth/youtube.upload"}; const char YouTubeService::SCOPES::YOUTUBEPARTNER[] = {"https://www.googleapis.com/auth/youtubepartner"}; const char YouTubeService::SCOPES::YOUTUBEPARTNER_CHANNEL_AUDIT[] = {"https://www.googleapis.com/auth/youtubepartner-channel-audit"}; YouTubeServiceBaseRequest::YouTubeServiceBaseRequest( const client::ClientService* service, client::AuthorizationCredential* credential, client::HttpRequest::HttpMethod method, const StringPiece& uri_template) : client::ClientServiceRequest( service, credential, method, uri_template), alt_("json"), pretty_print_(true), _have_alt_(false), _have_fields_(false), _have_key_(false), _have_oauth_token_(false), _have_pretty_print_(false), _have_quota_user_(false), _have_user_ip_(false) { } YouTubeServiceBaseRequest::~YouTubeServiceBaseRequest() { } util::Status YouTubeServiceBaseRequest::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return client::StatusInvalidArgument( StrCat("Unknown url variable='", variable_name, "'")); } util::Status YouTubeServiceBaseRequest::AppendOptionalQueryParameters( string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_alt_) { StrAppend(target, sep, "alt=", client::CppValueToEscapedUrlValue( alt_)); sep = "&"; } if (_have_fields_) { StrAppend(target, sep, "fields=", client::CppValueToEscapedUrlValue( fields_)); sep = "&"; } if (_have_key_) { StrAppend(target, sep, "key=", client::CppValueToEscapedUrlValue( key_)); sep = "&"; } if (_have_oauth_token_) { StrAppend(target, sep, "oauth_token=", client::CppValueToEscapedUrlValue( oauth_token_)); sep = "&"; } if (_have_pretty_print_) { StrAppend(target, sep, "prettyPrint=", client::CppValueToEscapedUrlValue( pretty_print_)); sep = "&"; } if (_have_quota_user_) { StrAppend(target, sep, "quotaUser=", client::CppValueToEscapedUrlValue( quota_user_)); sep = "&"; } if (_have_user_ip_) { StrAppend(target, sep, "userIp=", client::CppValueToEscapedUrlValue( user_ip_)); sep = "&"; } return client::ClientServiceRequest ::AppendOptionalQueryParameters(target); } void YouTubeServiceBaseRequest::AddJsonContentToRequest( const client::JsonCppData *content) { client::HttpRequest* _http_request_ = mutable_http_request(); _http_request_->set_content_type( client::HttpRequest::ContentType_JSON); _http_request_->set_content_reader(content->MakeJsonReader()); } // Standard constructor. ActivitiesResource_InsertMethod::ActivitiesResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Activity& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "activities"), part_(part.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. ActivitiesResource_InsertMethod::~ActivitiesResource_InsertMethod() { } util::Status ActivitiesResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ActivitiesResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ActivitiesResource_ListMethod::ActivitiesResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "activities"), part_(part.as_string()), max_results_(5), _have_channel_id_(false), _have_home_(false), _have_max_results_(false), _have_mine_(false), _have_page_token_(false), _have_published_after_(false), _have_published_before_(false), _have_region_code_(false) { } // Standard destructor. ActivitiesResource_ListMethod::~ActivitiesResource_ListMethod() { } util::Status ActivitiesResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_channel_id_) { StrAppend(target, sep, "channelId=", client::CppValueToEscapedUrlValue( channel_id_)); sep = "&"; } if (_have_home_) { StrAppend(target, sep, "home=", client::CppValueToEscapedUrlValue( home_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_mine_) { StrAppend(target, sep, "mine=", client::CppValueToEscapedUrlValue( mine_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_published_after_) { StrAppend(target, sep, "publishedAfter=", client::CppValueToEscapedUrlValue( published_after_)); sep = "&"; } if (_have_published_before_) { StrAppend(target, sep, "publishedBefore=", client::CppValueToEscapedUrlValue( published_before_)); sep = "&"; } if (_have_region_code_) { StrAppend(target, sep, "regionCode=", client::CppValueToEscapedUrlValue( region_code_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ActivitiesResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CaptionsResource_DeleteMethod::CaptionsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "captions"), id_(id.as_string()), _have_on_behalf_of_(false), _have_on_behalf_of_content_owner_(false) { } // Standard destructor. CaptionsResource_DeleteMethod::~CaptionsResource_DeleteMethod() { } util::Status CaptionsResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; if (_have_on_behalf_of_) { StrAppend(target, sep, "onBehalfOf=", client::CppValueToEscapedUrlValue( on_behalf_of_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CaptionsResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CaptionsResource_DownloadMethod::CaptionsResource_DownloadMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "captions/{id}"), id_(id.as_string()), _have_on_behalf_of_(false), _have_on_behalf_of_content_owner_(false), _have_tfmt_(false), _have_tlang_(false) { } // Standard destructor. CaptionsResource_DownloadMethod::~CaptionsResource_DownloadMethod() { } util::Status CaptionsResource_DownloadMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_on_behalf_of_) { StrAppend(target, sep, "onBehalfOf=", client::CppValueToEscapedUrlValue( on_behalf_of_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_tfmt_) { StrAppend(target, sep, "tfmt=", client::CppValueToEscapedUrlValue( tfmt_)); sep = "&"; } if (_have_tlang_) { StrAppend(target, sep, "tlang=", client::CppValueToEscapedUrlValue( tlang_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CaptionsResource_DownloadMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "id") { client::UriTemplate::AppendValue( id_, config, target); return client::StatusOk(); } return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // static const client::MediaUploadSpec CaptionsResource_InsertMethod::SIMPLE_MEDIA_UPLOAD( "simple", "/upload/youtube/v3/captions", true); // static const client::MediaUploadSpec CaptionsResource_InsertMethod::RESUMABLE_MEDIA_UPLOAD( "resumable", "/resumable/upload/youtube/v3/captions", true); // Deprecated constructor did not take media upload arguments. CaptionsResource_InsertMethod::CaptionsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "captions"), part_(part.as_string()), _have_on_behalf_of_(false), _have_on_behalf_of_content_owner_(false), _have_sync_(false) { uploader_.reset(new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "captions"))); } // Standard constructor. CaptionsResource_InsertMethod::CaptionsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Caption* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "captions"), part_(part.as_string()), _have_on_behalf_of_(false), _have_on_behalf_of_content_owner_(false), _have_sync_(false) { if (_media_content_reader_) { client::MediaUploader* uploader = new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "captions")); if (_metadata_) { uploader->set_metadata(*_metadata_); } uploader->set_media_content_reader( _media_content_type_.as_string(), _media_content_reader_); ResetMediaUploader(uploader); } else { AddJsonContentToRequest(_metadata_); } } // Standard destructor. CaptionsResource_InsertMethod::~CaptionsResource_InsertMethod() { } util::Status CaptionsResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_) { StrAppend(target, sep, "onBehalfOf=", client::CppValueToEscapedUrlValue( on_behalf_of_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_sync_) { StrAppend(target, sep, "sync=", client::CppValueToEscapedUrlValue( sync_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CaptionsResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CaptionsResource_ListMethod::CaptionsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const StringPiece& video_id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "captions"), part_(part.as_string()), video_id_(video_id.as_string()), _have_id_(false), _have_on_behalf_of_(false), _have_on_behalf_of_content_owner_(false) { } // Standard destructor. CaptionsResource_ListMethod::~CaptionsResource_ListMethod() { } util::Status CaptionsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; StrAppend(target, sep, "videoId=", client::CppValueToEscapedUrlValue( video_id_)); sep = "&"; if (_have_id_) { StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; } if (_have_on_behalf_of_) { StrAppend(target, sep, "onBehalfOf=", client::CppValueToEscapedUrlValue( on_behalf_of_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CaptionsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // static const client::MediaUploadSpec CaptionsResource_UpdateMethod::SIMPLE_MEDIA_UPLOAD( "simple", "/upload/youtube/v3/captions", true); // static const client::MediaUploadSpec CaptionsResource_UpdateMethod::RESUMABLE_MEDIA_UPLOAD( "resumable", "/resumable/upload/youtube/v3/captions", true); // Deprecated constructor did not take media upload arguments. CaptionsResource_UpdateMethod::CaptionsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "captions"), part_(part.as_string()), _have_on_behalf_of_(false), _have_on_behalf_of_content_owner_(false), _have_sync_(false) { uploader_.reset(new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "captions"))); } // Standard constructor. CaptionsResource_UpdateMethod::CaptionsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Caption* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "captions"), part_(part.as_string()), _have_on_behalf_of_(false), _have_on_behalf_of_content_owner_(false), _have_sync_(false) { if (_media_content_reader_) { client::MediaUploader* uploader = new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "captions")); if (_metadata_) { uploader->set_metadata(*_metadata_); } uploader->set_media_content_reader( _media_content_type_.as_string(), _media_content_reader_); ResetMediaUploader(uploader); } else { AddJsonContentToRequest(_metadata_); } } // Standard destructor. CaptionsResource_UpdateMethod::~CaptionsResource_UpdateMethod() { } util::Status CaptionsResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_) { StrAppend(target, sep, "onBehalfOf=", client::CppValueToEscapedUrlValue( on_behalf_of_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_sync_) { StrAppend(target, sep, "sync=", client::CppValueToEscapedUrlValue( sync_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CaptionsResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // static const client::MediaUploadSpec ChannelBannersResource_InsertMethod::SIMPLE_MEDIA_UPLOAD( "simple", "/upload/youtube/v3/channelBanners/insert", true); // static const client::MediaUploadSpec ChannelBannersResource_InsertMethod::RESUMABLE_MEDIA_UPLOAD( "resumable", "/resumable/upload/youtube/v3/channelBanners/insert", true); // Deprecated constructor did not take media upload arguments. ChannelBannersResource_InsertMethod::ChannelBannersResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "channelBanners/insert"), _have_on_behalf_of_content_owner_(false) { uploader_.reset(new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "channelBanners/insert"))); } // Standard constructor. ChannelBannersResource_InsertMethod::ChannelBannersResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const ChannelBannerResource* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "channelBanners/insert"), _have_on_behalf_of_content_owner_(false) { if (_media_content_reader_) { client::MediaUploader* uploader = new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "channelBanners/insert")); if (_metadata_) { uploader->set_metadata(*_metadata_); } uploader->set_media_content_reader( _media_content_type_.as_string(), _media_content_reader_); ResetMediaUploader(uploader); } else { AddJsonContentToRequest(_metadata_); } } // Standard destructor. ChannelBannersResource_InsertMethod::~ChannelBannersResource_InsertMethod() { } util::Status ChannelBannersResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ChannelBannersResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ChannelSectionsResource_DeleteMethod::ChannelSectionsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "channelSections"), id_(id.as_string()), _have_on_behalf_of_content_owner_(false) { } // Standard destructor. ChannelSectionsResource_DeleteMethod::~ChannelSectionsResource_DeleteMethod() { } util::Status ChannelSectionsResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ChannelSectionsResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ChannelSectionsResource_InsertMethod::ChannelSectionsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const ChannelSection& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "channelSections"), part_(part.as_string()), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. ChannelSectionsResource_InsertMethod::~ChannelSectionsResource_InsertMethod() { } util::Status ChannelSectionsResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ChannelSectionsResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ChannelSectionsResource_ListMethod::ChannelSectionsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "channelSections"), part_(part.as_string()), _have_channel_id_(false), _have_hl_(false), _have_id_(false), _have_mine_(false), _have_on_behalf_of_content_owner_(false) { } // Standard destructor. ChannelSectionsResource_ListMethod::~ChannelSectionsResource_ListMethod() { } util::Status ChannelSectionsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_channel_id_) { StrAppend(target, sep, "channelId=", client::CppValueToEscapedUrlValue( channel_id_)); sep = "&"; } if (_have_hl_) { StrAppend(target, sep, "hl=", client::CppValueToEscapedUrlValue( hl_)); sep = "&"; } if (_have_id_) { StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; } if (_have_mine_) { StrAppend(target, sep, "mine=", client::CppValueToEscapedUrlValue( mine_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ChannelSectionsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ChannelSectionsResource_UpdateMethod::ChannelSectionsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const ChannelSection& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "channelSections"), part_(part.as_string()), _have_on_behalf_of_content_owner_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. ChannelSectionsResource_UpdateMethod::~ChannelSectionsResource_UpdateMethod() { } util::Status ChannelSectionsResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ChannelSectionsResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ChannelsResource_ListMethod::ChannelsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "channels"), part_(part.as_string()), max_results_(5), _have_category_id_(false), _have_for_username_(false), _have_hl_(false), _have_id_(false), _have_managed_by_me_(false), _have_max_results_(false), _have_mine_(false), _have_my_subscribers_(false), _have_on_behalf_of_content_owner_(false), _have_page_token_(false) { } // Standard destructor. ChannelsResource_ListMethod::~ChannelsResource_ListMethod() { } util::Status ChannelsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_category_id_) { StrAppend(target, sep, "categoryId=", client::CppValueToEscapedUrlValue( category_id_)); sep = "&"; } if (_have_for_username_) { StrAppend(target, sep, "forUsername=", client::CppValueToEscapedUrlValue( for_username_)); sep = "&"; } if (_have_hl_) { StrAppend(target, sep, "hl=", client::CppValueToEscapedUrlValue( hl_)); sep = "&"; } if (_have_id_) { StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; } if (_have_managed_by_me_) { StrAppend(target, sep, "managedByMe=", client::CppValueToEscapedUrlValue( managed_by_me_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_mine_) { StrAppend(target, sep, "mine=", client::CppValueToEscapedUrlValue( mine_)); sep = "&"; } if (_have_my_subscribers_) { StrAppend(target, sep, "mySubscribers=", client::CppValueToEscapedUrlValue( my_subscribers_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ChannelsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ChannelsResource_UpdateMethod::ChannelsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Channel& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "channels"), part_(part.as_string()), _have_on_behalf_of_content_owner_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. ChannelsResource_UpdateMethod::~ChannelsResource_UpdateMethod() { } util::Status ChannelsResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ChannelsResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CommentThreadsResource_InsertMethod::CommentThreadsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const CommentThread& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "commentThreads"), part_(part.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. CommentThreadsResource_InsertMethod::~CommentThreadsResource_InsertMethod() { } util::Status CommentThreadsResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CommentThreadsResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CommentThreadsResource_ListMethod::CommentThreadsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "commentThreads"), part_(part.as_string()), max_results_(20), moderation_status_("MODERATION_STATUS_PUBLISHED"), order_("true"), text_format_("FORMAT_HTML"), _have_all_threads_related_to_channel_id_(false), _have_channel_id_(false), _have_id_(false), _have_max_results_(false), _have_moderation_status_(false), _have_order_(false), _have_page_token_(false), _have_search_terms_(false), _have_text_format_(false), _have_video_id_(false) { } // Standard destructor. CommentThreadsResource_ListMethod::~CommentThreadsResource_ListMethod() { } util::Status CommentThreadsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_all_threads_related_to_channel_id_) { StrAppend(target, sep, "allThreadsRelatedToChannelId=", client::CppValueToEscapedUrlValue( all_threads_related_to_channel_id_)); sep = "&"; } if (_have_channel_id_) { StrAppend(target, sep, "channelId=", client::CppValueToEscapedUrlValue( channel_id_)); sep = "&"; } if (_have_id_) { StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_moderation_status_) { StrAppend(target, sep, "moderationStatus=", client::CppValueToEscapedUrlValue( moderation_status_)); sep = "&"; } if (_have_order_) { StrAppend(target, sep, "order=", client::CppValueToEscapedUrlValue( order_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_search_terms_) { StrAppend(target, sep, "searchTerms=", client::CppValueToEscapedUrlValue( search_terms_)); sep = "&"; } if (_have_text_format_) { StrAppend(target, sep, "textFormat=", client::CppValueToEscapedUrlValue( text_format_)); sep = "&"; } if (_have_video_id_) { StrAppend(target, sep, "videoId=", client::CppValueToEscapedUrlValue( video_id_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CommentThreadsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CommentThreadsResource_UpdateMethod::CommentThreadsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const CommentThread& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "commentThreads"), part_(part.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. CommentThreadsResource_UpdateMethod::~CommentThreadsResource_UpdateMethod() { } util::Status CommentThreadsResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CommentThreadsResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CommentsResource_DeleteMethod::CommentsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "comments"), id_(id.as_string()) { } // Standard destructor. CommentsResource_DeleteMethod::~CommentsResource_DeleteMethod() { } util::Status CommentsResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CommentsResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CommentsResource_InsertMethod::CommentsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Comment& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "comments"), part_(part.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. CommentsResource_InsertMethod::~CommentsResource_InsertMethod() { } util::Status CommentsResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CommentsResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CommentsResource_ListMethod::CommentsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "comments"), part_(part.as_string()), max_results_(20), text_format_("FORMAT_HTML"), _have_id_(false), _have_max_results_(false), _have_page_token_(false), _have_parent_id_(false), _have_text_format_(false) { } // Standard destructor. CommentsResource_ListMethod::~CommentsResource_ListMethod() { } util::Status CommentsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_id_) { StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_parent_id_) { StrAppend(target, sep, "parentId=", client::CppValueToEscapedUrlValue( parent_id_)); sep = "&"; } if (_have_text_format_) { StrAppend(target, sep, "textFormat=", client::CppValueToEscapedUrlValue( text_format_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CommentsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CommentsResource_MarkAsSpamMethod::CommentsResource_MarkAsSpamMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "comments/markAsSpam"), id_(id.as_string()) { } // Standard destructor. CommentsResource_MarkAsSpamMethod::~CommentsResource_MarkAsSpamMethod() { } util::Status CommentsResource_MarkAsSpamMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CommentsResource_MarkAsSpamMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CommentsResource_SetModerationStatusMethod::CommentsResource_SetModerationStatusMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& moderation_status) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "comments/setModerationStatus"), id_(id.as_string()), moderation_status_(moderation_status.as_string()), ban_author_(false), _have_ban_author_(false) { } // Standard destructor. CommentsResource_SetModerationStatusMethod::~CommentsResource_SetModerationStatusMethod() { } util::Status CommentsResource_SetModerationStatusMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; StrAppend(target, sep, "moderationStatus=", client::CppValueToEscapedUrlValue( moderation_status_)); sep = "&"; if (_have_ban_author_) { StrAppend(target, sep, "banAuthor=", client::CppValueToEscapedUrlValue( ban_author_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CommentsResource_SetModerationStatusMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CommentsResource_UpdateMethod::CommentsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Comment& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "comments"), part_(part.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. CommentsResource_UpdateMethod::~CommentsResource_UpdateMethod() { } util::Status CommentsResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CommentsResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. FanFundingEventsResource_ListMethod::FanFundingEventsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "fanFundingEvents"), part_(part.as_string()), max_results_(5), _have_hl_(false), _have_max_results_(false), _have_page_token_(false) { } // Standard destructor. FanFundingEventsResource_ListMethod::~FanFundingEventsResource_ListMethod() { } util::Status FanFundingEventsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_hl_) { StrAppend(target, sep, "hl=", client::CppValueToEscapedUrlValue( hl_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status FanFundingEventsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. GuideCategoriesResource_ListMethod::GuideCategoriesResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "guideCategories"), part_(part.as_string()), hl_("en-US"), _have_hl_(false), _have_id_(false), _have_region_code_(false) { } // Standard destructor. GuideCategoriesResource_ListMethod::~GuideCategoriesResource_ListMethod() { } util::Status GuideCategoriesResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_hl_) { StrAppend(target, sep, "hl=", client::CppValueToEscapedUrlValue( hl_)); sep = "&"; } if (_have_id_) { StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; } if (_have_region_code_) { StrAppend(target, sep, "regionCode=", client::CppValueToEscapedUrlValue( region_code_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status GuideCategoriesResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. I18nLanguagesResource_ListMethod::I18nLanguagesResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "i18nLanguages"), part_(part.as_string()), hl_("en_US"), _have_hl_(false) { } // Standard destructor. I18nLanguagesResource_ListMethod::~I18nLanguagesResource_ListMethod() { } util::Status I18nLanguagesResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_hl_) { StrAppend(target, sep, "hl=", client::CppValueToEscapedUrlValue( hl_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status I18nLanguagesResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. I18nRegionsResource_ListMethod::I18nRegionsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "i18nRegions"), part_(part.as_string()), hl_("en_US"), _have_hl_(false) { } // Standard destructor. I18nRegionsResource_ListMethod::~I18nRegionsResource_ListMethod() { } util::Status I18nRegionsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_hl_) { StrAppend(target, sep, "hl=", client::CppValueToEscapedUrlValue( hl_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status I18nRegionsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveBroadcastsResource_BindMethod::LiveBroadcastsResource_BindMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "liveBroadcasts/bind"), id_(id.as_string()), part_(part.as_string()), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false), _have_stream_id_(false) { } // Standard destructor. LiveBroadcastsResource_BindMethod::~LiveBroadcastsResource_BindMethod() { } util::Status LiveBroadcastsResource_BindMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } if (_have_stream_id_) { StrAppend(target, sep, "streamId=", client::CppValueToEscapedUrlValue( stream_id_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveBroadcastsResource_BindMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveBroadcastsResource_ControlMethod::LiveBroadcastsResource_ControlMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "liveBroadcasts/control"), id_(id.as_string()), part_(part.as_string()), _have_display_slate_(false), _have_offset_time_ms_(false), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false), _have_walltime_(false) { } // Standard destructor. LiveBroadcastsResource_ControlMethod::~LiveBroadcastsResource_ControlMethod() { } util::Status LiveBroadcastsResource_ControlMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_display_slate_) { StrAppend(target, sep, "displaySlate=", client::CppValueToEscapedUrlValue( display_slate_)); sep = "&"; } if (_have_offset_time_ms_) { StrAppend(target, sep, "offsetTimeMs=", client::CppValueToEscapedUrlValue( offset_time_ms_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } if (_have_walltime_) { StrAppend(target, sep, "walltime=", client::CppValueToEscapedUrlValue( walltime_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveBroadcastsResource_ControlMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveBroadcastsResource_DeleteMethod::LiveBroadcastsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "liveBroadcasts"), id_(id.as_string()), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false) { } // Standard destructor. LiveBroadcastsResource_DeleteMethod::~LiveBroadcastsResource_DeleteMethod() { } util::Status LiveBroadcastsResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveBroadcastsResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveBroadcastsResource_InsertMethod::LiveBroadcastsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveBroadcast& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "liveBroadcasts"), part_(part.as_string()), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. LiveBroadcastsResource_InsertMethod::~LiveBroadcastsResource_InsertMethod() { } util::Status LiveBroadcastsResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveBroadcastsResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveBroadcastsResource_ListMethod::LiveBroadcastsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "liveBroadcasts"), part_(part.as_string()), broadcast_type_("BROADCAST_TYPE_FILTER_EVENT"), max_results_(5), _have_broadcast_status_(false), _have_broadcast_type_(false), _have_id_(false), _have_max_results_(false), _have_mine_(false), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false), _have_page_token_(false) { } // Standard destructor. LiveBroadcastsResource_ListMethod::~LiveBroadcastsResource_ListMethod() { } util::Status LiveBroadcastsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_broadcast_status_) { StrAppend(target, sep, "broadcastStatus=", client::CppValueToEscapedUrlValue( broadcast_status_)); sep = "&"; } if (_have_broadcast_type_) { StrAppend(target, sep, "broadcastType=", client::CppValueToEscapedUrlValue( broadcast_type_)); sep = "&"; } if (_have_id_) { StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_mine_) { StrAppend(target, sep, "mine=", client::CppValueToEscapedUrlValue( mine_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveBroadcastsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveBroadcastsResource_TransitionMethod::LiveBroadcastsResource_TransitionMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& broadcast_status, const StringPiece& id, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "liveBroadcasts/transition"), broadcast_status_(broadcast_status.as_string()), id_(id.as_string()), part_(part.as_string()), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false) { } // Standard destructor. LiveBroadcastsResource_TransitionMethod::~LiveBroadcastsResource_TransitionMethod() { } util::Status LiveBroadcastsResource_TransitionMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "broadcastStatus=", client::CppValueToEscapedUrlValue( broadcast_status_)); sep = "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveBroadcastsResource_TransitionMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveBroadcastsResource_UpdateMethod::LiveBroadcastsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveBroadcast& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "liveBroadcasts"), part_(part.as_string()), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. LiveBroadcastsResource_UpdateMethod::~LiveBroadcastsResource_UpdateMethod() { } util::Status LiveBroadcastsResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveBroadcastsResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveChatBansResource_DeleteMethod::LiveChatBansResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "liveChat/bans"), id_(id.as_string()) { } // Standard destructor. LiveChatBansResource_DeleteMethod::~LiveChatBansResource_DeleteMethod() { } util::Status LiveChatBansResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveChatBansResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveChatBansResource_InsertMethod::LiveChatBansResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveChatBan& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "liveChat/bans"), part_(part.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. LiveChatBansResource_InsertMethod::~LiveChatBansResource_InsertMethod() { } util::Status LiveChatBansResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveChatBansResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveChatMessagesResource_DeleteMethod::LiveChatMessagesResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "liveChat/messages"), id_(id.as_string()) { } // Standard destructor. LiveChatMessagesResource_DeleteMethod::~LiveChatMessagesResource_DeleteMethod() { } util::Status LiveChatMessagesResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveChatMessagesResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveChatMessagesResource_InsertMethod::LiveChatMessagesResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveChatMessage& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "liveChat/messages"), part_(part.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. LiveChatMessagesResource_InsertMethod::~LiveChatMessagesResource_InsertMethod() { } util::Status LiveChatMessagesResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveChatMessagesResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveChatMessagesResource_ListMethod::LiveChatMessagesResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& live_chat_id, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "liveChat/messages"), live_chat_id_(live_chat_id.as_string()), part_(part.as_string()), max_results_(500), _have_hl_(false), _have_max_results_(false), _have_page_token_(false), _have_profile_image_size_(false) { } // Standard destructor. LiveChatMessagesResource_ListMethod::~LiveChatMessagesResource_ListMethod() { } util::Status LiveChatMessagesResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "liveChatId=", client::CppValueToEscapedUrlValue( live_chat_id_)); sep = "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_hl_) { StrAppend(target, sep, "hl=", client::CppValueToEscapedUrlValue( hl_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_profile_image_size_) { StrAppend(target, sep, "profileImageSize=", client::CppValueToEscapedUrlValue( profile_image_size_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveChatMessagesResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveChatModeratorsResource_DeleteMethod::LiveChatModeratorsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "liveChat/moderators"), id_(id.as_string()) { } // Standard destructor. LiveChatModeratorsResource_DeleteMethod::~LiveChatModeratorsResource_DeleteMethod() { } util::Status LiveChatModeratorsResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveChatModeratorsResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveChatModeratorsResource_InsertMethod::LiveChatModeratorsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveChatModerator& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "liveChat/moderators"), part_(part.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. LiveChatModeratorsResource_InsertMethod::~LiveChatModeratorsResource_InsertMethod() { } util::Status LiveChatModeratorsResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveChatModeratorsResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveChatModeratorsResource_ListMethod::LiveChatModeratorsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& live_chat_id, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "liveChat/moderators"), live_chat_id_(live_chat_id.as_string()), part_(part.as_string()), max_results_(5), _have_max_results_(false), _have_page_token_(false) { } // Standard destructor. LiveChatModeratorsResource_ListMethod::~LiveChatModeratorsResource_ListMethod() { } util::Status LiveChatModeratorsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "liveChatId=", client::CppValueToEscapedUrlValue( live_chat_id_)); sep = "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveChatModeratorsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveStreamsResource_DeleteMethod::LiveStreamsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "liveStreams"), id_(id.as_string()), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false) { } // Standard destructor. LiveStreamsResource_DeleteMethod::~LiveStreamsResource_DeleteMethod() { } util::Status LiveStreamsResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveStreamsResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveStreamsResource_InsertMethod::LiveStreamsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveStream& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "liveStreams"), part_(part.as_string()), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. LiveStreamsResource_InsertMethod::~LiveStreamsResource_InsertMethod() { } util::Status LiveStreamsResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveStreamsResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveStreamsResource_ListMethod::LiveStreamsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "liveStreams"), part_(part.as_string()), max_results_(5), _have_id_(false), _have_max_results_(false), _have_mine_(false), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false), _have_page_token_(false) { } // Standard destructor. LiveStreamsResource_ListMethod::~LiveStreamsResource_ListMethod() { } util::Status LiveStreamsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_id_) { StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_mine_) { StrAppend(target, sep, "mine=", client::CppValueToEscapedUrlValue( mine_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveStreamsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. LiveStreamsResource_UpdateMethod::LiveStreamsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveStream& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "liveStreams"), part_(part.as_string()), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. LiveStreamsResource_UpdateMethod::~LiveStreamsResource_UpdateMethod() { } util::Status LiveStreamsResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status LiveStreamsResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PlaylistItemsResource_DeleteMethod::PlaylistItemsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "playlistItems"), id_(id.as_string()), _have_on_behalf_of_content_owner_(false) { } // Standard destructor. PlaylistItemsResource_DeleteMethod::~PlaylistItemsResource_DeleteMethod() { } util::Status PlaylistItemsResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PlaylistItemsResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PlaylistItemsResource_InsertMethod::PlaylistItemsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const PlaylistItem& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "playlistItems"), part_(part.as_string()), _have_on_behalf_of_content_owner_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. PlaylistItemsResource_InsertMethod::~PlaylistItemsResource_InsertMethod() { } util::Status PlaylistItemsResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PlaylistItemsResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PlaylistItemsResource_ListMethod::PlaylistItemsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "playlistItems"), part_(part.as_string()), max_results_(5), _have_id_(false), _have_max_results_(false), _have_on_behalf_of_content_owner_(false), _have_page_token_(false), _have_playlist_id_(false), _have_video_id_(false) { } // Standard destructor. PlaylistItemsResource_ListMethod::~PlaylistItemsResource_ListMethod() { } util::Status PlaylistItemsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_id_) { StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_playlist_id_) { StrAppend(target, sep, "playlistId=", client::CppValueToEscapedUrlValue( playlist_id_)); sep = "&"; } if (_have_video_id_) { StrAppend(target, sep, "videoId=", client::CppValueToEscapedUrlValue( video_id_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PlaylistItemsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PlaylistItemsResource_UpdateMethod::PlaylistItemsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const PlaylistItem& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "playlistItems"), part_(part.as_string()), _have_on_behalf_of_content_owner_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. PlaylistItemsResource_UpdateMethod::~PlaylistItemsResource_UpdateMethod() { } util::Status PlaylistItemsResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PlaylistItemsResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PlaylistsResource_DeleteMethod::PlaylistsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "playlists"), id_(id.as_string()), _have_on_behalf_of_content_owner_(false) { } // Standard destructor. PlaylistsResource_DeleteMethod::~PlaylistsResource_DeleteMethod() { } util::Status PlaylistsResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PlaylistsResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PlaylistsResource_InsertMethod::PlaylistsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Playlist& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "playlists"), part_(part.as_string()), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. PlaylistsResource_InsertMethod::~PlaylistsResource_InsertMethod() { } util::Status PlaylistsResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PlaylistsResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PlaylistsResource_ListMethod::PlaylistsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "playlists"), part_(part.as_string()), max_results_(5), _have_channel_id_(false), _have_hl_(false), _have_id_(false), _have_max_results_(false), _have_mine_(false), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false), _have_page_token_(false) { } // Standard destructor. PlaylistsResource_ListMethod::~PlaylistsResource_ListMethod() { } util::Status PlaylistsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_channel_id_) { StrAppend(target, sep, "channelId=", client::CppValueToEscapedUrlValue( channel_id_)); sep = "&"; } if (_have_hl_) { StrAppend(target, sep, "hl=", client::CppValueToEscapedUrlValue( hl_)); sep = "&"; } if (_have_id_) { StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_mine_) { StrAppend(target, sep, "mine=", client::CppValueToEscapedUrlValue( mine_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PlaylistsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PlaylistsResource_UpdateMethod::PlaylistsResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Playlist& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "playlists"), part_(part.as_string()), _have_on_behalf_of_content_owner_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. PlaylistsResource_UpdateMethod::~PlaylistsResource_UpdateMethod() { } util::Status PlaylistsResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PlaylistsResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. SearchResource_ListMethod::SearchResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "search"), part_(part.as_string()), max_results_(5), order_("SEARCH_SORT_RELEVANCE"), type_("video,channel,playlist"), _have_channel_id_(false), _have_channel_type_(false), _have_event_type_(false), _have_for_content_owner_(false), _have_for_developer_(false), _have_for_mine_(false), _have_location_(false), _have_location_radius_(false), _have_max_results_(false), _have_on_behalf_of_content_owner_(false), _have_order_(false), _have_page_token_(false), _have_published_after_(false), _have_published_before_(false), _have_q_(false), _have_region_code_(false), _have_related_to_video_id_(false), _have_relevance_language_(false), _have_safe_search_(false), _have_topic_id_(false), _have_type_(false), _have_video_caption_(false), _have_video_category_id_(false), _have_video_definition_(false), _have_video_dimension_(false), _have_video_duration_(false), _have_video_embeddable_(false), _have_video_license_(false), _have_video_syndicated_(false), _have_video_type_(false) { } // Standard destructor. SearchResource_ListMethod::~SearchResource_ListMethod() { } util::Status SearchResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_channel_id_) { StrAppend(target, sep, "channelId=", client::CppValueToEscapedUrlValue( channel_id_)); sep = "&"; } if (_have_channel_type_) { StrAppend(target, sep, "channelType=", client::CppValueToEscapedUrlValue( channel_type_)); sep = "&"; } if (_have_event_type_) { StrAppend(target, sep, "eventType=", client::CppValueToEscapedUrlValue( event_type_)); sep = "&"; } if (_have_for_content_owner_) { StrAppend(target, sep, "forContentOwner=", client::CppValueToEscapedUrlValue( for_content_owner_)); sep = "&"; } if (_have_for_developer_) { StrAppend(target, sep, "forDeveloper=", client::CppValueToEscapedUrlValue( for_developer_)); sep = "&"; } if (_have_for_mine_) { StrAppend(target, sep, "forMine=", client::CppValueToEscapedUrlValue( for_mine_)); sep = "&"; } if (_have_location_) { StrAppend(target, sep, "location=", client::CppValueToEscapedUrlValue( location_)); sep = "&"; } if (_have_location_radius_) { StrAppend(target, sep, "locationRadius=", client::CppValueToEscapedUrlValue( location_radius_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_order_) { StrAppend(target, sep, "order=", client::CppValueToEscapedUrlValue( order_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_published_after_) { StrAppend(target, sep, "publishedAfter=", client::CppValueToEscapedUrlValue( published_after_)); sep = "&"; } if (_have_published_before_) { StrAppend(target, sep, "publishedBefore=", client::CppValueToEscapedUrlValue( published_before_)); sep = "&"; } if (_have_q_) { StrAppend(target, sep, "q=", client::CppValueToEscapedUrlValue( q_)); sep = "&"; } if (_have_region_code_) { StrAppend(target, sep, "regionCode=", client::CppValueToEscapedUrlValue( region_code_)); sep = "&"; } if (_have_related_to_video_id_) { StrAppend(target, sep, "relatedToVideoId=", client::CppValueToEscapedUrlValue( related_to_video_id_)); sep = "&"; } if (_have_relevance_language_) { StrAppend(target, sep, "relevanceLanguage=", client::CppValueToEscapedUrlValue( relevance_language_)); sep = "&"; } if (_have_safe_search_) { StrAppend(target, sep, "safeSearch=", client::CppValueToEscapedUrlValue( safe_search_)); sep = "&"; } if (_have_topic_id_) { StrAppend(target, sep, "topicId=", client::CppValueToEscapedUrlValue( topic_id_)); sep = "&"; } if (_have_type_) { StrAppend(target, sep, "type=", client::CppValueToEscapedUrlValue( type_)); sep = "&"; } if (_have_video_caption_) { StrAppend(target, sep, "videoCaption=", client::CppValueToEscapedUrlValue( video_caption_)); sep = "&"; } if (_have_video_category_id_) { StrAppend(target, sep, "videoCategoryId=", client::CppValueToEscapedUrlValue( video_category_id_)); sep = "&"; } if (_have_video_definition_) { StrAppend(target, sep, "videoDefinition=", client::CppValueToEscapedUrlValue( video_definition_)); sep = "&"; } if (_have_video_dimension_) { StrAppend(target, sep, "videoDimension=", client::CppValueToEscapedUrlValue( video_dimension_)); sep = "&"; } if (_have_video_duration_) { StrAppend(target, sep, "videoDuration=", client::CppValueToEscapedUrlValue( video_duration_)); sep = "&"; } if (_have_video_embeddable_) { StrAppend(target, sep, "videoEmbeddable=", client::CppValueToEscapedUrlValue( video_embeddable_)); sep = "&"; } if (_have_video_license_) { StrAppend(target, sep, "videoLicense=", client::CppValueToEscapedUrlValue( video_license_)); sep = "&"; } if (_have_video_syndicated_) { StrAppend(target, sep, "videoSyndicated=", client::CppValueToEscapedUrlValue( video_syndicated_)); sep = "&"; } if (_have_video_type_) { StrAppend(target, sep, "videoType=", client::CppValueToEscapedUrlValue( video_type_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status SearchResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. SponsorsResource_ListMethod::SponsorsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "sponsors"), part_(part.as_string()), filter_("POLL_NEWEST"), max_results_(5), _have_filter_(false), _have_max_results_(false), _have_page_token_(false) { } // Standard destructor. SponsorsResource_ListMethod::~SponsorsResource_ListMethod() { } util::Status SponsorsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_filter_) { StrAppend(target, sep, "filter=", client::CppValueToEscapedUrlValue( filter_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status SponsorsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. SubscriptionsResource_DeleteMethod::SubscriptionsResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "subscriptions"), id_(id.as_string()) { } // Standard destructor. SubscriptionsResource_DeleteMethod::~SubscriptionsResource_DeleteMethod() { } util::Status SubscriptionsResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status SubscriptionsResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. SubscriptionsResource_InsertMethod::SubscriptionsResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Subscription& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "subscriptions"), part_(part.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. SubscriptionsResource_InsertMethod::~SubscriptionsResource_InsertMethod() { } util::Status SubscriptionsResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status SubscriptionsResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. SubscriptionsResource_ListMethod::SubscriptionsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "subscriptions"), part_(part.as_string()), max_results_(5), order_("SUBSCRIPTION_ORDER_RELEVANCE"), _have_channel_id_(false), _have_for_channel_id_(false), _have_id_(false), _have_max_results_(false), _have_mine_(false), _have_my_recent_subscribers_(false), _have_my_subscribers_(false), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false), _have_order_(false), _have_page_token_(false) { } // Standard destructor. SubscriptionsResource_ListMethod::~SubscriptionsResource_ListMethod() { } util::Status SubscriptionsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_channel_id_) { StrAppend(target, sep, "channelId=", client::CppValueToEscapedUrlValue( channel_id_)); sep = "&"; } if (_have_for_channel_id_) { StrAppend(target, sep, "forChannelId=", client::CppValueToEscapedUrlValue( for_channel_id_)); sep = "&"; } if (_have_id_) { StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_mine_) { StrAppend(target, sep, "mine=", client::CppValueToEscapedUrlValue( mine_)); sep = "&"; } if (_have_my_recent_subscribers_) { StrAppend(target, sep, "myRecentSubscribers=", client::CppValueToEscapedUrlValue( my_recent_subscribers_)); sep = "&"; } if (_have_my_subscribers_) { StrAppend(target, sep, "mySubscribers=", client::CppValueToEscapedUrlValue( my_subscribers_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } if (_have_order_) { StrAppend(target, sep, "order=", client::CppValueToEscapedUrlValue( order_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status SubscriptionsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. SuperChatEventsResource_ListMethod::SuperChatEventsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "superChatEvents"), part_(part.as_string()), max_results_(5), _have_hl_(false), _have_max_results_(false), _have_page_token_(false) { } // Standard destructor. SuperChatEventsResource_ListMethod::~SuperChatEventsResource_ListMethod() { } util::Status SuperChatEventsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_hl_) { StrAppend(target, sep, "hl=", client::CppValueToEscapedUrlValue( hl_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status SuperChatEventsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // static const client::MediaUploadSpec ThumbnailsResource_SetMethod::SIMPLE_MEDIA_UPLOAD( "simple", "/upload/youtube/v3/thumbnails/set", true); // static const client::MediaUploadSpec ThumbnailsResource_SetMethod::RESUMABLE_MEDIA_UPLOAD( "resumable", "/resumable/upload/youtube/v3/thumbnails/set", true); // Standard constructor. ThumbnailsResource_SetMethod::ThumbnailsResource_SetMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& video_id, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "thumbnails/set"), video_id_(video_id.as_string()), _have_on_behalf_of_content_owner_(false) { if (_media_content_reader_) { client::MediaUploader* uploader = new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "thumbnails/set")); uploader->set_media_content_reader( _media_content_type_.as_string(), _media_content_reader_); ResetMediaUploader(uploader); } } // Standard destructor. ThumbnailsResource_SetMethod::~ThumbnailsResource_SetMethod() { } util::Status ThumbnailsResource_SetMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "videoId=", client::CppValueToEscapedUrlValue( video_id_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ThumbnailsResource_SetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. VideoAbuseReportReasonsResource_ListMethod::VideoAbuseReportReasonsResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "videoAbuseReportReasons"), part_(part.as_string()), hl_("en_US"), _have_hl_(false) { } // Standard destructor. VideoAbuseReportReasonsResource_ListMethod::~VideoAbuseReportReasonsResource_ListMethod() { } util::Status VideoAbuseReportReasonsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_hl_) { StrAppend(target, sep, "hl=", client::CppValueToEscapedUrlValue( hl_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status VideoAbuseReportReasonsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. VideoCategoriesResource_ListMethod::VideoCategoriesResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "videoCategories"), part_(part.as_string()), hl_("en_US"), _have_hl_(false), _have_id_(false), _have_region_code_(false) { } // Standard destructor. VideoCategoriesResource_ListMethod::~VideoCategoriesResource_ListMethod() { } util::Status VideoCategoriesResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_hl_) { StrAppend(target, sep, "hl=", client::CppValueToEscapedUrlValue( hl_)); sep = "&"; } if (_have_id_) { StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; } if (_have_region_code_) { StrAppend(target, sep, "regionCode=", client::CppValueToEscapedUrlValue( region_code_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status VideoCategoriesResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. VideosResource_DeleteMethod::VideosResource_DeleteMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "videos"), id_(id.as_string()), _have_on_behalf_of_content_owner_(false) { } // Standard destructor. VideosResource_DeleteMethod::~VideosResource_DeleteMethod() { } util::Status VideosResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status VideosResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. VideosResource_GetRatingMethod::VideosResource_GetRatingMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "videos/getRating"), id_(id.as_string()), _have_on_behalf_of_content_owner_(false) { } // Standard destructor. VideosResource_GetRatingMethod::~VideosResource_GetRatingMethod() { } util::Status VideosResource_GetRatingMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status VideosResource_GetRatingMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // static const client::MediaUploadSpec VideosResource_InsertMethod::SIMPLE_MEDIA_UPLOAD( "simple", "/upload/youtube/v3/videos", true); // static const client::MediaUploadSpec VideosResource_InsertMethod::RESUMABLE_MEDIA_UPLOAD( "resumable", "/resumable/upload/youtube/v3/videos", true); // Deprecated constructor did not take media upload arguments. VideosResource_InsertMethod::VideosResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "videos"), part_(part.as_string()), notify_subscribers_(true), _have_auto_levels_(false), _have_notify_subscribers_(false), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false), _have_stabilize_(false) { uploader_.reset(new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "videos"))); } // Standard constructor. VideosResource_InsertMethod::VideosResource_InsertMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Video* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "videos"), part_(part.as_string()), notify_subscribers_(true), _have_auto_levels_(false), _have_notify_subscribers_(false), _have_on_behalf_of_content_owner_(false), _have_on_behalf_of_content_owner_channel_(false), _have_stabilize_(false) { if (_media_content_reader_) { client::MediaUploader* uploader = new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "videos")); if (_metadata_) { uploader->set_metadata(*_metadata_); } uploader->set_media_content_reader( _media_content_type_.as_string(), _media_content_reader_); ResetMediaUploader(uploader); } else { AddJsonContentToRequest(_metadata_); } } // Standard destructor. VideosResource_InsertMethod::~VideosResource_InsertMethod() { } util::Status VideosResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_auto_levels_) { StrAppend(target, sep, "autoLevels=", client::CppValueToEscapedUrlValue( auto_levels_)); sep = "&"; } if (_have_notify_subscribers_) { StrAppend(target, sep, "notifySubscribers=", client::CppValueToEscapedUrlValue( notify_subscribers_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_on_behalf_of_content_owner_channel_) { StrAppend(target, sep, "onBehalfOfContentOwnerChannel=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_channel_)); sep = "&"; } if (_have_stabilize_) { StrAppend(target, sep, "stabilize=", client::CppValueToEscapedUrlValue( stabilize_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status VideosResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. VideosResource_ListMethod::VideosResource_ListMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "videos"), part_(part.as_string()), max_results_(5), video_category_id_("0"), _have_chart_(false), _have_hl_(false), _have_id_(false), _have_locale_(false), _have_max_height_(false), _have_max_results_(false), _have_max_width_(false), _have_my_rating_(false), _have_on_behalf_of_content_owner_(false), _have_page_token_(false), _have_region_code_(false), _have_video_category_id_(false) { } // Standard destructor. VideosResource_ListMethod::~VideosResource_ListMethod() { } util::Status VideosResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_chart_) { StrAppend(target, sep, "chart=", client::CppValueToEscapedUrlValue( chart_)); sep = "&"; } if (_have_hl_) { StrAppend(target, sep, "hl=", client::CppValueToEscapedUrlValue( hl_)); sep = "&"; } if (_have_id_) { StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; } if (_have_locale_) { StrAppend(target, sep, "locale=", client::CppValueToEscapedUrlValue( locale_)); sep = "&"; } if (_have_max_height_) { StrAppend(target, sep, "maxHeight=", client::CppValueToEscapedUrlValue( max_height_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_max_width_) { StrAppend(target, sep, "maxWidth=", client::CppValueToEscapedUrlValue( max_width_)); sep = "&"; } if (_have_my_rating_) { StrAppend(target, sep, "myRating=", client::CppValueToEscapedUrlValue( my_rating_)); sep = "&"; } if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_region_code_) { StrAppend(target, sep, "regionCode=", client::CppValueToEscapedUrlValue( region_code_)); sep = "&"; } if (_have_video_category_id_) { StrAppend(target, sep, "videoCategoryId=", client::CppValueToEscapedUrlValue( video_category_id_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status VideosResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. VideosResource_RateMethod::VideosResource_RateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& rating) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "videos/rate"), id_(id.as_string()), rating_(rating.as_string()) { } // Standard destructor. VideosResource_RateMethod::~VideosResource_RateMethod() { } util::Status VideosResource_RateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "id=", client::CppValueToEscapedUrlValue( id_)); sep = "&"; StrAppend(target, sep, "rating=", client::CppValueToEscapedUrlValue( rating_)); sep = "&"; return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status VideosResource_RateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. VideosResource_ReportAbuseMethod::VideosResource_ReportAbuseMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const VideoAbuseReport& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "videos/reportAbuse"), _have_on_behalf_of_content_owner_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. VideosResource_ReportAbuseMethod::~VideosResource_ReportAbuseMethod() { } util::Status VideosResource_ReportAbuseMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status VideosResource_ReportAbuseMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. VideosResource_UpdateMethod::VideosResource_UpdateMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& part, const Video& __request_content__) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "videos"), part_(part.as_string()), _have_on_behalf_of_content_owner_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. VideosResource_UpdateMethod::~VideosResource_UpdateMethod() { } util::Status VideosResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "part=", client::CppValueToEscapedUrlValue( part_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status VideosResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // static const client::MediaUploadSpec WatermarksResource_SetMethod::SIMPLE_MEDIA_UPLOAD( "simple", "/upload/youtube/v3/watermarks/set", true); // static const client::MediaUploadSpec WatermarksResource_SetMethod::RESUMABLE_MEDIA_UPLOAD( "resumable", "/resumable/upload/youtube/v3/watermarks/set", true); // Deprecated constructor did not take media upload arguments. WatermarksResource_SetMethod::WatermarksResource_SetMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& channel_id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "watermarks/set"), channel_id_(channel_id.as_string()), _have_on_behalf_of_content_owner_(false) { uploader_.reset(new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "watermarks/set"))); } // Standard constructor. WatermarksResource_SetMethod::WatermarksResource_SetMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& channel_id, const InvideoBranding* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "watermarks/set"), channel_id_(channel_id.as_string()), _have_on_behalf_of_content_owner_(false) { if (_media_content_reader_) { client::MediaUploader* uploader = new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "watermarks/set")); if (_metadata_) { uploader->set_metadata(*_metadata_); } uploader->set_media_content_reader( _media_content_type_.as_string(), _media_content_reader_); ResetMediaUploader(uploader); } else { AddJsonContentToRequest(_metadata_); } } // Standard destructor. WatermarksResource_SetMethod::~WatermarksResource_SetMethod() { } util::Status WatermarksResource_SetMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "channelId=", client::CppValueToEscapedUrlValue( channel_id_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status WatermarksResource_SetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. WatermarksResource_UnsetMethod::WatermarksResource_UnsetMethod( const YouTubeService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& channel_id) : YouTubeServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "watermarks/unset"), channel_id_(channel_id.as_string()), _have_on_behalf_of_content_owner_(false) { } // Standard destructor. WatermarksResource_UnsetMethod::~WatermarksResource_UnsetMethod() { } util::Status WatermarksResource_UnsetMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "channelId=", client::CppValueToEscapedUrlValue( channel_id_)); sep = "&"; if (_have_on_behalf_of_content_owner_) { StrAppend(target, sep, "onBehalfOfContentOwner=", client::CppValueToEscapedUrlValue( on_behalf_of_content_owner_)); sep = "&"; } return YouTubeServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status WatermarksResource_UnsetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return YouTubeServiceBaseRequest::AppendVariable( variable_name, config, target); } YouTubeService::YouTubeService(client::HttpTransport* transport) : ClientService("https://www.googleapis.com/", "youtube/v3/", transport), activities_(this), captions_(this), channel_banners_(this), channel_sections_(this), channels_(this), comment_threads_(this), comments_(this), fan_funding_events_(this), guide_categories_(this), i18n_languages_(this), i18n_regions_(this), live_broadcasts_(this), live_chat_bans_(this), live_chat_messages_(this), live_chat_moderators_(this), live_streams_(this), playlist_items_(this), playlists_(this), search_(this), sponsors_(this), subscriptions_(this), super_chat_events_(this), thumbnails_(this), video_abuse_report_reasons_(this), video_categories_(this), videos_(this), watermarks_(this) { } YouTubeService::~YouTubeService() { } YouTubeService::ActivitiesResource::ActivitiesResource(YouTubeService* service) : service_(service) { } ActivitiesResource_InsertMethod* YouTubeService::ActivitiesResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const Activity& __request_content__) const { return new ActivitiesResource_InsertMethod(service_, _credential_, part, __request_content__); } ActivitiesResource_ListMethod* YouTubeService::ActivitiesResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new ActivitiesResource_ListMethod(service_, _credential_, part); } ActivitiesResource_ListMethodPager* YouTubeService::ActivitiesResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<ActivitiesResource_ListMethod, ActivityListResponse>(new ActivitiesResource_ListMethod(service_, _credential_, part)); } YouTubeService::CaptionsResource::CaptionsResource(YouTubeService* service) : service_(service) { } CaptionsResource_DeleteMethod* YouTubeService::CaptionsResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& id) const { return new CaptionsResource_DeleteMethod(service_, _credential_, id); } CaptionsResource_DownloadMethod* YouTubeService::CaptionsResource::NewDownloadMethod(client::AuthorizationCredential* _credential_, const StringPiece& id) const { return new CaptionsResource_DownloadMethod(service_, _credential_, id); } // This factory method is deprecated in favor of the newer variation that // also takes the media upload parameters. CaptionsResource_InsertMethod* YouTubeService::CaptionsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new CaptionsResource_InsertMethod(service_, _credential_, part); } CaptionsResource_InsertMethod* YouTubeService::CaptionsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const Caption* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const { return new CaptionsResource_InsertMethod(service_, _credential_, part, _metadata_, _media_content_type_, _media_content_reader_); } CaptionsResource_ListMethod* YouTubeService::CaptionsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const StringPiece& video_id) const { return new CaptionsResource_ListMethod(service_, _credential_, part, video_id); } // This factory method is deprecated in favor of the newer variation that // also takes the media upload parameters. CaptionsResource_UpdateMethod* YouTubeService::CaptionsResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new CaptionsResource_UpdateMethod(service_, _credential_, part); } CaptionsResource_UpdateMethod* YouTubeService::CaptionsResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const Caption* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const { return new CaptionsResource_UpdateMethod(service_, _credential_, part, _metadata_, _media_content_type_, _media_content_reader_); } YouTubeService::ChannelBannersResource::ChannelBannersResource(YouTubeService* service) : service_(service) { } // This factory method is deprecated in favor of the newer variation that // also takes the media upload parameters. ChannelBannersResource_InsertMethod* YouTubeService::ChannelBannersResource::NewInsertMethod(client::AuthorizationCredential* _credential_) const { return new ChannelBannersResource_InsertMethod(service_, _credential_); } ChannelBannersResource_InsertMethod* YouTubeService::ChannelBannersResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const ChannelBannerResource* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const { return new ChannelBannersResource_InsertMethod(service_, _credential_, _metadata_, _media_content_type_, _media_content_reader_); } YouTubeService::ChannelSectionsResource::ChannelSectionsResource(YouTubeService* service) : service_(service) { } ChannelSectionsResource_DeleteMethod* YouTubeService::ChannelSectionsResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& id) const { return new ChannelSectionsResource_DeleteMethod(service_, _credential_, id); } ChannelSectionsResource_InsertMethod* YouTubeService::ChannelSectionsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const ChannelSection& __request_content__) const { return new ChannelSectionsResource_InsertMethod(service_, _credential_, part, __request_content__); } ChannelSectionsResource_ListMethod* YouTubeService::ChannelSectionsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new ChannelSectionsResource_ListMethod(service_, _credential_, part); } ChannelSectionsResource_UpdateMethod* YouTubeService::ChannelSectionsResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const ChannelSection& __request_content__) const { return new ChannelSectionsResource_UpdateMethod(service_, _credential_, part, __request_content__); } YouTubeService::ChannelsResource::ChannelsResource(YouTubeService* service) : service_(service) { } ChannelsResource_ListMethod* YouTubeService::ChannelsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new ChannelsResource_ListMethod(service_, _credential_, part); } ChannelsResource_ListMethodPager* YouTubeService::ChannelsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<ChannelsResource_ListMethod, ChannelListResponse>(new ChannelsResource_ListMethod(service_, _credential_, part)); } ChannelsResource_UpdateMethod* YouTubeService::ChannelsResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const Channel& __request_content__) const { return new ChannelsResource_UpdateMethod(service_, _credential_, part, __request_content__); } YouTubeService::CommentThreadsResource::CommentThreadsResource(YouTubeService* service) : service_(service) { } CommentThreadsResource_InsertMethod* YouTubeService::CommentThreadsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const CommentThread& __request_content__) const { return new CommentThreadsResource_InsertMethod(service_, _credential_, part, __request_content__); } CommentThreadsResource_ListMethod* YouTubeService::CommentThreadsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new CommentThreadsResource_ListMethod(service_, _credential_, part); } CommentThreadsResource_ListMethodPager* YouTubeService::CommentThreadsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<CommentThreadsResource_ListMethod, CommentThreadListResponse>(new CommentThreadsResource_ListMethod(service_, _credential_, part)); } CommentThreadsResource_UpdateMethod* YouTubeService::CommentThreadsResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const CommentThread& __request_content__) const { return new CommentThreadsResource_UpdateMethod(service_, _credential_, part, __request_content__); } YouTubeService::CommentsResource::CommentsResource(YouTubeService* service) : service_(service) { } CommentsResource_DeleteMethod* YouTubeService::CommentsResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& id) const { return new CommentsResource_DeleteMethod(service_, _credential_, id); } CommentsResource_InsertMethod* YouTubeService::CommentsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const Comment& __request_content__) const { return new CommentsResource_InsertMethod(service_, _credential_, part, __request_content__); } CommentsResource_ListMethod* YouTubeService::CommentsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new CommentsResource_ListMethod(service_, _credential_, part); } CommentsResource_ListMethodPager* YouTubeService::CommentsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<CommentsResource_ListMethod, CommentListResponse>(new CommentsResource_ListMethod(service_, _credential_, part)); } CommentsResource_MarkAsSpamMethod* YouTubeService::CommentsResource::NewMarkAsSpamMethod(client::AuthorizationCredential* _credential_, const StringPiece& id) const { return new CommentsResource_MarkAsSpamMethod(service_, _credential_, id); } CommentsResource_SetModerationStatusMethod* YouTubeService::CommentsResource::NewSetModerationStatusMethod(client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& moderation_status) const { return new CommentsResource_SetModerationStatusMethod(service_, _credential_, id, moderation_status); } CommentsResource_UpdateMethod* YouTubeService::CommentsResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const Comment& __request_content__) const { return new CommentsResource_UpdateMethod(service_, _credential_, part, __request_content__); } YouTubeService::FanFundingEventsResource::FanFundingEventsResource(YouTubeService* service) : service_(service) { } FanFundingEventsResource_ListMethod* YouTubeService::FanFundingEventsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new FanFundingEventsResource_ListMethod(service_, _credential_, part); } FanFundingEventsResource_ListMethodPager* YouTubeService::FanFundingEventsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<FanFundingEventsResource_ListMethod, FanFundingEventListResponse>(new FanFundingEventsResource_ListMethod(service_, _credential_, part)); } YouTubeService::GuideCategoriesResource::GuideCategoriesResource(YouTubeService* service) : service_(service) { } GuideCategoriesResource_ListMethod* YouTubeService::GuideCategoriesResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new GuideCategoriesResource_ListMethod(service_, _credential_, part); } YouTubeService::I18nLanguagesResource::I18nLanguagesResource(YouTubeService* service) : service_(service) { } I18nLanguagesResource_ListMethod* YouTubeService::I18nLanguagesResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new I18nLanguagesResource_ListMethod(service_, _credential_, part); } YouTubeService::I18nRegionsResource::I18nRegionsResource(YouTubeService* service) : service_(service) { } I18nRegionsResource_ListMethod* YouTubeService::I18nRegionsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new I18nRegionsResource_ListMethod(service_, _credential_, part); } YouTubeService::LiveBroadcastsResource::LiveBroadcastsResource(YouTubeService* service) : service_(service) { } LiveBroadcastsResource_BindMethod* YouTubeService::LiveBroadcastsResource::NewBindMethod(client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& part) const { return new LiveBroadcastsResource_BindMethod(service_, _credential_, id, part); } LiveBroadcastsResource_ControlMethod* YouTubeService::LiveBroadcastsResource::NewControlMethod(client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& part) const { return new LiveBroadcastsResource_ControlMethod(service_, _credential_, id, part); } LiveBroadcastsResource_DeleteMethod* YouTubeService::LiveBroadcastsResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& id) const { return new LiveBroadcastsResource_DeleteMethod(service_, _credential_, id); } LiveBroadcastsResource_InsertMethod* YouTubeService::LiveBroadcastsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveBroadcast& __request_content__) const { return new LiveBroadcastsResource_InsertMethod(service_, _credential_, part, __request_content__); } LiveBroadcastsResource_ListMethod* YouTubeService::LiveBroadcastsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new LiveBroadcastsResource_ListMethod(service_, _credential_, part); } LiveBroadcastsResource_ListMethodPager* YouTubeService::LiveBroadcastsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<LiveBroadcastsResource_ListMethod, LiveBroadcastListResponse>(new LiveBroadcastsResource_ListMethod(service_, _credential_, part)); } LiveBroadcastsResource_TransitionMethod* YouTubeService::LiveBroadcastsResource::NewTransitionMethod(client::AuthorizationCredential* _credential_, const StringPiece& broadcast_status, const StringPiece& id, const StringPiece& part) const { return new LiveBroadcastsResource_TransitionMethod(service_, _credential_, broadcast_status, id, part); } LiveBroadcastsResource_UpdateMethod* YouTubeService::LiveBroadcastsResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveBroadcast& __request_content__) const { return new LiveBroadcastsResource_UpdateMethod(service_, _credential_, part, __request_content__); } YouTubeService::LiveChatBansResource::LiveChatBansResource(YouTubeService* service) : service_(service) { } LiveChatBansResource_DeleteMethod* YouTubeService::LiveChatBansResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& id) const { return new LiveChatBansResource_DeleteMethod(service_, _credential_, id); } LiveChatBansResource_InsertMethod* YouTubeService::LiveChatBansResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveChatBan& __request_content__) const { return new LiveChatBansResource_InsertMethod(service_, _credential_, part, __request_content__); } YouTubeService::LiveChatMessagesResource::LiveChatMessagesResource(YouTubeService* service) : service_(service) { } LiveChatMessagesResource_DeleteMethod* YouTubeService::LiveChatMessagesResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& id) const { return new LiveChatMessagesResource_DeleteMethod(service_, _credential_, id); } LiveChatMessagesResource_InsertMethod* YouTubeService::LiveChatMessagesResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveChatMessage& __request_content__) const { return new LiveChatMessagesResource_InsertMethod(service_, _credential_, part, __request_content__); } LiveChatMessagesResource_ListMethod* YouTubeService::LiveChatMessagesResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& live_chat_id, const StringPiece& part) const { return new LiveChatMessagesResource_ListMethod(service_, _credential_, live_chat_id, part); } LiveChatMessagesResource_ListMethodPager* YouTubeService::LiveChatMessagesResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& live_chat_id, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<LiveChatMessagesResource_ListMethod, LiveChatMessageListResponse>(new LiveChatMessagesResource_ListMethod(service_, _credential_, live_chat_id, part)); } YouTubeService::LiveChatModeratorsResource::LiveChatModeratorsResource(YouTubeService* service) : service_(service) { } LiveChatModeratorsResource_DeleteMethod* YouTubeService::LiveChatModeratorsResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& id) const { return new LiveChatModeratorsResource_DeleteMethod(service_, _credential_, id); } LiveChatModeratorsResource_InsertMethod* YouTubeService::LiveChatModeratorsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveChatModerator& __request_content__) const { return new LiveChatModeratorsResource_InsertMethod(service_, _credential_, part, __request_content__); } LiveChatModeratorsResource_ListMethod* YouTubeService::LiveChatModeratorsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& live_chat_id, const StringPiece& part) const { return new LiveChatModeratorsResource_ListMethod(service_, _credential_, live_chat_id, part); } LiveChatModeratorsResource_ListMethodPager* YouTubeService::LiveChatModeratorsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& live_chat_id, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<LiveChatModeratorsResource_ListMethod, LiveChatModeratorListResponse>(new LiveChatModeratorsResource_ListMethod(service_, _credential_, live_chat_id, part)); } YouTubeService::LiveStreamsResource::LiveStreamsResource(YouTubeService* service) : service_(service) { } LiveStreamsResource_DeleteMethod* YouTubeService::LiveStreamsResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& id) const { return new LiveStreamsResource_DeleteMethod(service_, _credential_, id); } LiveStreamsResource_InsertMethod* YouTubeService::LiveStreamsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveStream& __request_content__) const { return new LiveStreamsResource_InsertMethod(service_, _credential_, part, __request_content__); } LiveStreamsResource_ListMethod* YouTubeService::LiveStreamsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new LiveStreamsResource_ListMethod(service_, _credential_, part); } LiveStreamsResource_ListMethodPager* YouTubeService::LiveStreamsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<LiveStreamsResource_ListMethod, LiveStreamListResponse>(new LiveStreamsResource_ListMethod(service_, _credential_, part)); } LiveStreamsResource_UpdateMethod* YouTubeService::LiveStreamsResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const LiveStream& __request_content__) const { return new LiveStreamsResource_UpdateMethod(service_, _credential_, part, __request_content__); } YouTubeService::PlaylistItemsResource::PlaylistItemsResource(YouTubeService* service) : service_(service) { } PlaylistItemsResource_DeleteMethod* YouTubeService::PlaylistItemsResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& id) const { return new PlaylistItemsResource_DeleteMethod(service_, _credential_, id); } PlaylistItemsResource_InsertMethod* YouTubeService::PlaylistItemsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const PlaylistItem& __request_content__) const { return new PlaylistItemsResource_InsertMethod(service_, _credential_, part, __request_content__); } PlaylistItemsResource_ListMethod* YouTubeService::PlaylistItemsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new PlaylistItemsResource_ListMethod(service_, _credential_, part); } PlaylistItemsResource_ListMethodPager* YouTubeService::PlaylistItemsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<PlaylistItemsResource_ListMethod, PlaylistItemListResponse>(new PlaylistItemsResource_ListMethod(service_, _credential_, part)); } PlaylistItemsResource_UpdateMethod* YouTubeService::PlaylistItemsResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const PlaylistItem& __request_content__) const { return new PlaylistItemsResource_UpdateMethod(service_, _credential_, part, __request_content__); } YouTubeService::PlaylistsResource::PlaylistsResource(YouTubeService* service) : service_(service) { } PlaylistsResource_DeleteMethod* YouTubeService::PlaylistsResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& id) const { return new PlaylistsResource_DeleteMethod(service_, _credential_, id); } PlaylistsResource_InsertMethod* YouTubeService::PlaylistsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const Playlist& __request_content__) const { return new PlaylistsResource_InsertMethod(service_, _credential_, part, __request_content__); } PlaylistsResource_ListMethod* YouTubeService::PlaylistsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new PlaylistsResource_ListMethod(service_, _credential_, part); } PlaylistsResource_ListMethodPager* YouTubeService::PlaylistsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<PlaylistsResource_ListMethod, PlaylistListResponse>(new PlaylistsResource_ListMethod(service_, _credential_, part)); } PlaylistsResource_UpdateMethod* YouTubeService::PlaylistsResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const Playlist& __request_content__) const { return new PlaylistsResource_UpdateMethod(service_, _credential_, part, __request_content__); } YouTubeService::SearchResource::SearchResource(YouTubeService* service) : service_(service) { } SearchResource_ListMethod* YouTubeService::SearchResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new SearchResource_ListMethod(service_, _credential_, part); } SearchResource_ListMethodPager* YouTubeService::SearchResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<SearchResource_ListMethod, SearchListResponse>(new SearchResource_ListMethod(service_, _credential_, part)); } YouTubeService::SponsorsResource::SponsorsResource(YouTubeService* service) : service_(service) { } SponsorsResource_ListMethod* YouTubeService::SponsorsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new SponsorsResource_ListMethod(service_, _credential_, part); } SponsorsResource_ListMethodPager* YouTubeService::SponsorsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<SponsorsResource_ListMethod, SponsorListResponse>(new SponsorsResource_ListMethod(service_, _credential_, part)); } YouTubeService::SubscriptionsResource::SubscriptionsResource(YouTubeService* service) : service_(service) { } SubscriptionsResource_DeleteMethod* YouTubeService::SubscriptionsResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& id) const { return new SubscriptionsResource_DeleteMethod(service_, _credential_, id); } SubscriptionsResource_InsertMethod* YouTubeService::SubscriptionsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const Subscription& __request_content__) const { return new SubscriptionsResource_InsertMethod(service_, _credential_, part, __request_content__); } SubscriptionsResource_ListMethod* YouTubeService::SubscriptionsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new SubscriptionsResource_ListMethod(service_, _credential_, part); } SubscriptionsResource_ListMethodPager* YouTubeService::SubscriptionsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<SubscriptionsResource_ListMethod, SubscriptionListResponse>(new SubscriptionsResource_ListMethod(service_, _credential_, part)); } YouTubeService::SuperChatEventsResource::SuperChatEventsResource(YouTubeService* service) : service_(service) { } SuperChatEventsResource_ListMethod* YouTubeService::SuperChatEventsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new SuperChatEventsResource_ListMethod(service_, _credential_, part); } SuperChatEventsResource_ListMethodPager* YouTubeService::SuperChatEventsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<SuperChatEventsResource_ListMethod, SuperChatEventListResponse>(new SuperChatEventsResource_ListMethod(service_, _credential_, part)); } YouTubeService::ThumbnailsResource::ThumbnailsResource(YouTubeService* service) : service_(service) { } ThumbnailsResource_SetMethod* YouTubeService::ThumbnailsResource::NewSetMethod(client::AuthorizationCredential* _credential_, const StringPiece& video_id, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const { return new ThumbnailsResource_SetMethod(service_, _credential_, video_id, _media_content_type_, _media_content_reader_); } YouTubeService::VideoAbuseReportReasonsResource::VideoAbuseReportReasonsResource(YouTubeService* service) : service_(service) { } VideoAbuseReportReasonsResource_ListMethod* YouTubeService::VideoAbuseReportReasonsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new VideoAbuseReportReasonsResource_ListMethod(service_, _credential_, part); } YouTubeService::VideoCategoriesResource::VideoCategoriesResource(YouTubeService* service) : service_(service) { } VideoCategoriesResource_ListMethod* YouTubeService::VideoCategoriesResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new VideoCategoriesResource_ListMethod(service_, _credential_, part); } YouTubeService::VideosResource::VideosResource(YouTubeService* service) : service_(service) { } VideosResource_DeleteMethod* YouTubeService::VideosResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& id) const { return new VideosResource_DeleteMethod(service_, _credential_, id); } VideosResource_GetRatingMethod* YouTubeService::VideosResource::NewGetRatingMethod(client::AuthorizationCredential* _credential_, const StringPiece& id) const { return new VideosResource_GetRatingMethod(service_, _credential_, id); } // This factory method is deprecated in favor of the newer variation that // also takes the media upload parameters. VideosResource_InsertMethod* YouTubeService::VideosResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new VideosResource_InsertMethod(service_, _credential_, part); } VideosResource_InsertMethod* YouTubeService::VideosResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const Video* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const { return new VideosResource_InsertMethod(service_, _credential_, part, _metadata_, _media_content_type_, _media_content_reader_); } VideosResource_ListMethod* YouTubeService::VideosResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new VideosResource_ListMethod(service_, _credential_, part); } VideosResource_ListMethodPager* YouTubeService::VideosResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& part) const { return new client::EncapsulatedServiceRequestPager<VideosResource_ListMethod, VideoListResponse>(new VideosResource_ListMethod(service_, _credential_, part)); } VideosResource_RateMethod* YouTubeService::VideosResource::NewRateMethod(client::AuthorizationCredential* _credential_, const StringPiece& id, const StringPiece& rating) const { return new VideosResource_RateMethod(service_, _credential_, id, rating); } VideosResource_ReportAbuseMethod* YouTubeService::VideosResource::NewReportAbuseMethod(client::AuthorizationCredential* _credential_, const VideoAbuseReport& __request_content__) const { return new VideosResource_ReportAbuseMethod(service_, _credential_, __request_content__); } VideosResource_UpdateMethod* YouTubeService::VideosResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& part, const Video& __request_content__) const { return new VideosResource_UpdateMethod(service_, _credential_, part, __request_content__); } YouTubeService::WatermarksResource::WatermarksResource(YouTubeService* service) : service_(service) { } // This factory method is deprecated in favor of the newer variation that // also takes the media upload parameters. WatermarksResource_SetMethod* YouTubeService::WatermarksResource::NewSetMethod(client::AuthorizationCredential* _credential_, const StringPiece& channel_id) const { return new WatermarksResource_SetMethod(service_, _credential_, channel_id); } WatermarksResource_SetMethod* YouTubeService::WatermarksResource::NewSetMethod(client::AuthorizationCredential* _credential_, const StringPiece& channel_id, const InvideoBranding* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const { return new WatermarksResource_SetMethod(service_, _credential_, channel_id, _metadata_, _media_content_type_, _media_content_reader_); } WatermarksResource_UnsetMethod* YouTubeService::WatermarksResource::NewUnsetMethod(client::AuthorizationCredential* _credential_, const StringPiece& channel_id) const { return new WatermarksResource_UnsetMethod(service_, _credential_, channel_id); } } // namespace google_youtube_api <file_sep>/service_apis/youtube/google/youtube_api/video_content_details_region_restriction.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_VIDEO_CONTENT_DETAILS_REGION_RESTRICTION_H_ #define GOOGLE_YOUTUBE_API_VIDEO_CONTENT_DETAILS_REGION_RESTRICTION_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * DEPRECATED Region restriction of the video. * * @ingroup DataObject */ class VideoContentDetailsRegionRestriction : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static VideoContentDetailsRegionRestriction* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoContentDetailsRegionRestriction(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoContentDetailsRegionRestriction(Json::Value* storage); /** * Standard destructor. */ virtual ~VideoContentDetailsRegionRestriction(); /** * Returns a string denoting the type of this data object. * * @return * <code>google_youtube_api::VideoContentDetailsRegionRestriction</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::VideoContentDetailsRegionRestriction"); } /** * Determine if the '<code>allowed</code>' attribute was set. * * @return true if the '<code>allowed</code>' attribute was set. */ bool has_allowed() const { return Storage().isMember("allowed"); } /** * Clears the '<code>allowed</code>' attribute. */ void clear_allowed() { MutableStorage()->removeMember("allowed"); } /** * Get a reference to the value of the '<code>allowed</code>' attribute. */ const client::JsonCppArray<string > get_allowed() const { const Json::Value& storage = Storage("allowed"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>allowed</code>' property. * * A list of region codes that identify countries where the video is viewable. * If this property is present and a country is not listed in its value, then * the video is blocked from appearing in that country. If this property is * present and contains an empty list, the video is blocked in all countries. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_allowed() { Json::Value* storage = MutableStorage("allowed"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>blocked</code>' attribute was set. * * @return true if the '<code>blocked</code>' attribute was set. */ bool has_blocked() const { return Storage().isMember("blocked"); } /** * Clears the '<code>blocked</code>' attribute. */ void clear_blocked() { MutableStorage()->removeMember("blocked"); } /** * Get a reference to the value of the '<code>blocked</code>' attribute. */ const client::JsonCppArray<string > get_blocked() const { const Json::Value& storage = Storage("blocked"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>blocked</code>' property. * * A list of region codes that identify countries where the video is blocked. * If this property is present and a country is not listed in its value, then * the video is viewable in that country. If this property is present and * contains an empty list, the video is viewable in all countries. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_blocked() { Json::Value* storage = MutableStorage("blocked"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } private: void operator=(const VideoContentDetailsRegionRestriction&); }; // VideoContentDetailsRegionRestriction } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_VIDEO_CONTENT_DETAILS_REGION_RESTRICTION_H_ <file_sep>/service_apis/youtube/google/youtube_api/channel_section_snippet.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_CHANNEL_SECTION_SNIPPET_H_ #define GOOGLE_YOUTUBE_API_CHANNEL_SECTION_SNIPPET_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/channel_section_localization.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Basic details about a channel section, including title, style and position. * * @ingroup DataObject */ class ChannelSectionSnippet : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static ChannelSectionSnippet* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelSectionSnippet(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelSectionSnippet(Json::Value* storage); /** * Standard destructor. */ virtual ~ChannelSectionSnippet(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::ChannelSectionSnippet</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::ChannelSectionSnippet"); } /** * Determine if the '<code>channelId</code>' attribute was set. * * @return true if the '<code>channelId</code>' attribute was set. */ bool has_channel_id() const { return Storage().isMember("channelId"); } /** * Clears the '<code>channelId</code>' attribute. */ void clear_channel_id() { MutableStorage()->removeMember("channelId"); } /** * Get the value of the '<code>channelId</code>' attribute. */ const StringPiece get_channel_id() const { const Json::Value& v = Storage("channelId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>channelId</code>' attribute. * * The ID that YouTube uses to uniquely identify the channel that published * the channel section. * * @param[in] value The new value. */ void set_channel_id(const StringPiece& value) { *MutableStorage("channelId") = value.data(); } /** * Determine if the '<code>defaultLanguage</code>' attribute was set. * * @return true if the '<code>defaultLanguage</code>' attribute was set. */ bool has_default_language() const { return Storage().isMember("defaultLanguage"); } /** * Clears the '<code>defaultLanguage</code>' attribute. */ void clear_default_language() { MutableStorage()->removeMember("defaultLanguage"); } /** * Get the value of the '<code>defaultLanguage</code>' attribute. */ const StringPiece get_default_language() const { const Json::Value& v = Storage("defaultLanguage"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>defaultLanguage</code>' attribute. * * The language of the channel section's default title and description. * * @param[in] value The new value. */ void set_default_language(const StringPiece& value) { *MutableStorage("defaultLanguage") = value.data(); } /** * Determine if the '<code>localized</code>' attribute was set. * * @return true if the '<code>localized</code>' attribute was set. */ bool has_localized() const { return Storage().isMember("localized"); } /** * Clears the '<code>localized</code>' attribute. */ void clear_localized() { MutableStorage()->removeMember("localized"); } /** * Get a reference to the value of the '<code>localized</code>' attribute. */ const ChannelSectionLocalization get_localized() const; /** * Gets a reference to a mutable value of the '<code>localized</code>' * property. * * Localized title, read-only. * * @return The result can be modified to change the attribute value. */ ChannelSectionLocalization mutable_localized(); /** * Determine if the '<code>position</code>' attribute was set. * * @return true if the '<code>position</code>' attribute was set. */ bool has_position() const { return Storage().isMember("position"); } /** * Clears the '<code>position</code>' attribute. */ void clear_position() { MutableStorage()->removeMember("position"); } /** * Get the value of the '<code>position</code>' attribute. */ uint32 get_position() const { const Json::Value& storage = Storage("position"); return client::JsonValueToCppValueHelper<uint32 >(storage); } /** * Change the '<code>position</code>' attribute. * * The position of the channel section in the channel. * * @param[in] value The new value. */ void set_position(uint32 value) { client::SetJsonValueFromCppValueHelper<uint32 >( value, MutableStorage("position")); } /** * Determine if the '<code>style</code>' attribute was set. * * @return true if the '<code>style</code>' attribute was set. */ bool has_style() const { return Storage().isMember("style"); } /** * Clears the '<code>style</code>' attribute. */ void clear_style() { MutableStorage()->removeMember("style"); } /** * Get the value of the '<code>style</code>' attribute. */ const StringPiece get_style() const { const Json::Value& v = Storage("style"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>style</code>' attribute. * * The style of the channel section. * * @param[in] value The new value. */ void set_style(const StringPiece& value) { *MutableStorage("style") = value.data(); } /** * Determine if the '<code>title</code>' attribute was set. * * @return true if the '<code>title</code>' attribute was set. */ bool has_title() const { return Storage().isMember("title"); } /** * Clears the '<code>title</code>' attribute. */ void clear_title() { MutableStorage()->removeMember("title"); } /** * Get the value of the '<code>title</code>' attribute. */ const StringPiece get_title() const { const Json::Value& v = Storage("title"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>title</code>' attribute. * * The channel section's title for multiple_playlists and multiple_channels. * * @param[in] value The new value. */ void set_title(const StringPiece& value) { *MutableStorage("title") = value.data(); } /** * Determine if the '<code>type</code>' attribute was set. * * @return true if the '<code>type</code>' attribute was set. */ bool has_type() const { return Storage().isMember("type"); } /** * Clears the '<code>type</code>' attribute. */ void clear_type() { MutableStorage()->removeMember("type"); } /** * Get the value of the '<code>type</code>' attribute. */ const StringPiece get_type() const { const Json::Value& v = Storage("type"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>type</code>' attribute. * * The type of the channel section. * * @param[in] value The new value. */ void set_type(const StringPiece& value) { *MutableStorage("type") = value.data(); } private: void operator=(const ChannelSectionSnippet&); }; // ChannelSectionSnippet } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_CHANNEL_SECTION_SNIPPET_H_ <file_sep>/service_apis/drive/google/drive_api/user.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Drive API (drive/v2) // Generated from: // Version: v2 // Revision: 20170512 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_DRIVE_API_USER_H_ #define GOOGLE_DRIVE_API_USER_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_drive_api { using namespace googleapis; /** * Information about a Drive user. * * @ingroup DataObject */ class User : public client::JsonCppData { public: /** * The user's profile picture. * * @ingroup DataObject */ class UserPicture : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static UserPicture* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit UserPicture(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit UserPicture(Json::Value* storage); /** * Standard destructor. */ virtual ~UserPicture(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::UserPicture</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::UserPicture"); } /** * Determine if the '<code>url</code>' attribute was set. * * @return true if the '<code>url</code>' attribute was set. */ bool has_url() const { return Storage().isMember("url"); } /** * Clears the '<code>url</code>' attribute. */ void clear_url() { MutableStorage()->removeMember("url"); } /** * Get the value of the '<code>url</code>' attribute. */ const StringPiece get_url() const { const Json::Value& v = Storage("url"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>url</code>' attribute. * * A URL that points to a profile picture of this user. * * @param[in] value The new value. */ void set_url(const StringPiece& value) { *MutableStorage("url") = value.data(); } private: void operator=(const UserPicture&); }; // UserPicture /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static User* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit User(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit User(Json::Value* storage); /** * Standard destructor. */ virtual ~User(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::User</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::User"); } /** * Determine if the '<code>displayName</code>' attribute was set. * * @return true if the '<code>displayName</code>' attribute was set. */ bool has_display_name() const { return Storage().isMember("displayName"); } /** * Clears the '<code>displayName</code>' attribute. */ void clear_display_name() { MutableStorage()->removeMember("displayName"); } /** * Get the value of the '<code>displayName</code>' attribute. */ const StringPiece get_display_name() const { const Json::Value& v = Storage("displayName"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>displayName</code>' attribute. * * A plain text displayable name for this user. * * @param[in] value The new value. */ void set_display_name(const StringPiece& value) { *MutableStorage("displayName") = value.data(); } /** * Determine if the '<code>emailAddress</code>' attribute was set. * * @return true if the '<code>emailAddress</code>' attribute was set. */ bool has_email_address() const { return Storage().isMember("emailAddress"); } /** * Clears the '<code>emailAddress</code>' attribute. */ void clear_email_address() { MutableStorage()->removeMember("emailAddress"); } /** * Get the value of the '<code>emailAddress</code>' attribute. */ const StringPiece get_email_address() const { const Json::Value& v = Storage("emailAddress"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>emailAddress</code>' attribute. * * The email address of the user. * * @param[in] value The new value. */ void set_email_address(const StringPiece& value) { *MutableStorage("emailAddress") = value.data(); } /** * Determine if the '<code>isAuthenticatedUser</code>' attribute was set. * * @return true if the '<code>isAuthenticatedUser</code>' attribute was set. */ bool has_is_authenticated_user() const { return Storage().isMember("isAuthenticatedUser"); } /** * Clears the '<code>isAuthenticatedUser</code>' attribute. */ void clear_is_authenticated_user() { MutableStorage()->removeMember("isAuthenticatedUser"); } /** * Get the value of the '<code>isAuthenticatedUser</code>' attribute. */ bool get_is_authenticated_user() const { const Json::Value& storage = Storage("isAuthenticatedUser"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>isAuthenticatedUser</code>' attribute. * * Whether this user is the same as the authenticated user for whom the * request was made. * * @param[in] value The new value. */ void set_is_authenticated_user(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("isAuthenticatedUser")); } /** * Determine if the '<code>kind</code>' attribute was set. * * @return true if the '<code>kind</code>' attribute was set. */ bool has_kind() const { return Storage().isMember("kind"); } /** * Clears the '<code>kind</code>' attribute. */ void clear_kind() { MutableStorage()->removeMember("kind"); } /** * Get the value of the '<code>kind</code>' attribute. */ const StringPiece get_kind() const { const Json::Value& v = Storage("kind"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kind</code>' attribute. * * This is always drive#user. * * @param[in] value The new value. */ void set_kind(const StringPiece& value) { *MutableStorage("kind") = value.data(); } /** * Determine if the '<code>permissionId</code>' attribute was set. * * @return true if the '<code>permissionId</code>' attribute was set. */ bool has_permission_id() const { return Storage().isMember("permissionId"); } /** * Clears the '<code>permissionId</code>' attribute. */ void clear_permission_id() { MutableStorage()->removeMember("permissionId"); } /** * Get the value of the '<code>permissionId</code>' attribute. */ const StringPiece get_permission_id() const { const Json::Value& v = Storage("permissionId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>permissionId</code>' attribute. * * The user's ID as visible in the permissions collection. * * @param[in] value The new value. */ void set_permission_id(const StringPiece& value) { *MutableStorage("permissionId") = value.data(); } /** * Determine if the '<code>picture</code>' attribute was set. * * @return true if the '<code>picture</code>' attribute was set. */ bool has_picture() const { return Storage().isMember("picture"); } /** * Clears the '<code>picture</code>' attribute. */ void clear_picture() { MutableStorage()->removeMember("picture"); } /** * Get a reference to the value of the '<code>picture</code>' attribute. */ const UserPicture get_picture() const { const Json::Value& storage = Storage("picture"); return client::JsonValueToCppValueHelper<UserPicture >(storage); } /** * Gets a reference to a mutable value of the '<code>picture</code>' property. * * The user's profile picture. * * @return The result can be modified to change the attribute value. */ UserPicture mutable_picture() { Json::Value* storage = MutableStorage("picture"); return client::JsonValueToMutableCppValueHelper<UserPicture >(storage); } private: void operator=(const User&); }; // User } // namespace google_drive_api #endif // GOOGLE_DRIVE_API_USER_H_ <file_sep>/service_apis/drive/google/drive_api/CMakeLists.txt # This is a CMake file for Drive API v2 # using the Google APIs Client Library for C++. # # See http://google.github.io/google-api-cpp-client/latest/start/get_started # for more information about what to do with this file. project (google_drive_api) # These sources assume that the CMakeLists.txt in ../.. added itself to # the include directories so that include paths are specified explicitly # with the directory #include "google/drive_api/..." add_library(google_drive_api STATIC about.cc app.cc app_list.cc change.cc change_list.cc channel.cc child_list.cc child_reference.cc comment.cc comment_list.cc comment_reply.cc comment_reply_list.cc file.cc file_list.cc generated_ids.cc parent_list.cc parent_reference.cc permission.cc permission_id.cc permission_list.cc property.cc property_list.cc revision.cc revision_list.cc start_page_token.cc team_drive.cc team_drive_list.cc user.cc drive_service.cc) target_link_libraries(google_drive_api googleapis_http) target_link_libraries(google_drive_api googleapis_internal) target_link_libraries(google_drive_api googleapis_jsoncpp) target_link_libraries(google_drive_api googleapis_utils) <file_sep>/src/googleapis/client/transport/test/http_request_batch_test.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <cstdio> #include <utility> #include <vector> #include "googleapis/client/data/data_reader.h" #include "googleapis/client/transport/http_request.h" #include "googleapis/client/transport/http_request_batch.h" #include "googleapis/client/transport/http_response.h" #include "googleapis/client/transport/test/mock_http_transport.h" #include "googleapis/client/util/status.h" #include "googleapis/strings/stringpiece.h" #include "googleapis/strings/strcat.h" #include "googleapis/strings/util.h" #include <gmock/gmock.h> #include <gtest/gtest.h> namespace googleapis { using testing::_; using testing::InvokeWithoutArgs; using testing::DoAll; using testing::Return; using client::AuthorizationCredential; using client::HttpRequestBatch; using client::DataReader; using client::HttpRequest; using client::HttpRequestCallback; using client::HttpResponse; using client::HttpStatusCode; using client::MockHttpRequest; using client::MockHttpTransport; using client::kCRLF; const char kAuthorizationHeader[] = "TestAuthorizationHeader"; class FakeCredential : public AuthorizationCredential { public: explicit FakeCredential(const StringPiece& value) : value_(value.as_string()) { } virtual ~FakeCredential() {} const string& fake_value() const { return value_; } virtual const string type() const { return "FAKE"; } virtual googleapis::util::Status Refresh() { LOG(FATAL) << "Not expected"; return client::StatusUnimplemented("Not expected"); } virtual void RefreshAsync(Callback1<util::Status>* callback) { LOG(FATAL) << "Not expected"; callback->Run(client::StatusUnimplemented("Not expected")); } virtual googleapis::util::Status Load(DataReader* reader) { LOG(FATAL) << "Not expected"; return client::StatusUnimplemented("Not expected"); } virtual DataReader* MakeDataReader() const { LOG(FATAL) << "Not expected"; return NULL; } virtual googleapis::util::Status AuthorizeRequest(HttpRequest* request) { request->AddHeader(kAuthorizationHeader, value_); return client::StatusOk(); } private: string value_; DISALLOW_COPY_AND_ASSIGN(FakeCredential); }; struct BatchTestCase { BatchTestCase(HttpRequest::HttpMethod meth, int code, FakeCredential* cred = NULL, HttpRequestCallback* cb = NULL) : method(meth), http_code(code), credential(cred), callback(cb), create_directly_in_batch(true), respond_out_of_order(false) { } HttpRequest::HttpMethod method; int http_code; FakeCredential* credential; HttpRequestCallback* callback; bool create_directly_in_batch; bool respond_out_of_order; // Defer my response until after the others. }; static void DeleteStrings(string* a, string* b, string* c) { delete a; delete b; delete c; } class BatchTestFixture : public testing::Test { protected: static void PokeResponseBody(string* body, HttpRequest* request) { EXPECT_TRUE(request->response()->body_writer()->Write(*body).ok()); } HttpRequestBatch* MakeBatchRequest( const std::vector<BatchTestCase>& method_and_response, FakeCredential* credential, string** mock_response_ptr = NULL) { MockHttpRequest* mock_request = new MockHttpRequest(HttpRequest::POST, &transport_); EXPECT_CALL(transport_, NewHttpRequest(HttpRequest::POST)) .WillOnce(Return(mock_request)); HttpRequestBatch* batch = new HttpRequestBatch(&transport_); const string response_boundary = "_xxxxxx_"; string* mock_response = new string; string* out_of_order_responses = new string; for (int i = 0; i < method_and_response.size(); ++i) { const BatchTestCase& test = method_and_response[i]; const string url = StrCat("http://test/", i); HttpRequest* batched_request; if (test.create_directly_in_batch) { batched_request = batch->NewHttpRequest(test.method, test.callback); } else { batched_request = new MockHttpRequest(test.method, &transport_); } batched_request->set_url(StrCat("http://test/", i)); for (int j = 0; j < 3; ++j) { batched_request->AddHeader( StrCat("TestHeader_", j), StrCat("Header Value ", j)); } if (!test.create_directly_in_batch) { // Turn the independent mock request into a batch request then // destroy the original mock and giving us the batched replacement. batched_request = batch->AddFromGenericRequestAndRetire( batched_request, test.callback); } // The response for this request. string this_mock_response; StrAppend(&this_mock_response, "--", response_boundary, kCRLF, "Content-Type: application/http", kCRLF, "Content-ID: <response-", HttpRequestBatch::PointerToHex(batched_request), ">", kCRLF); StrAppend(&this_mock_response, kCRLF, "HTTP/1.1 ", test.http_code, " StatusSummary", kCRLF); StrAppend(&this_mock_response, "ResponseHeaderA: response A.", i, kCRLF, "ResponseHeaderB: response B.", i, kCRLF, kCRLF, "Response Body ", i); if (test.respond_out_of_order) { if (!out_of_order_responses->empty()) { StrAppend(out_of_order_responses, kCRLF); } StrAppend(out_of_order_responses, this_mock_response); } else { if (!mock_response->empty()) { StrAppend(mock_response, kCRLF); } StrAppend(mock_response, this_mock_response); } } if (!out_of_order_responses->empty()) { StrAppend(mock_response, kCRLF); StrAppend(mock_response, *out_of_order_responses); } StrAppend(mock_response, kCRLF, "--", response_boundary, "--", kCRLF); Closure* poke_http_code = NewCallback(mock_request, &MockHttpRequest::poke_http_code, 200); string* contenttype = new string( StrCat("multipart/mixed; boundary=", response_boundary)); Closure* poke_response_header = NewCallback(mock_request, &MockHttpRequest::poke_response_header, "Content-Type", *contenttype); Closure* poke_response_body = NewCallback(*PokeResponseBody, mock_response, mock_request); Closure* delete_strings = NewCallback(&DeleteStrings, mock_response, out_of_order_responses, contenttype); EXPECT_CALL(*mock_request, DoExecute(_)) .WillOnce(DoAll( InvokeWithoutArgs(poke_http_code, &Closure::Run), InvokeWithoutArgs(poke_response_header, &Closure::Run), InvokeWithoutArgs(poke_response_body, &Closure::Run), InvokeWithoutArgs(delete_strings, &Closure::Run))); if (mock_response_ptr) { *mock_response_ptr = mock_response; } return batch; } void CheckResponse( const std::vector<BatchTestCase>& tests, const std::vector<HttpRequest*>& parts) { for (int i = 0; i < tests.size(); ++i) { HttpResponse* response = parts[i]->response(); EXPECT_EQ(tests[i].http_code, response->http_code()); CheckResponseContent(response, i); } } void CheckResponseContent(HttpResponse* response, int position) { DataReader* reader = response->body_reader(); EXPECT_TRUE(reader != NULL); if (reader == NULL) return; EXPECT_EQ(StrCat("Response Body ", position), reader->RemainderToString()); const string* value; value = response->FindHeaderValue("ResponseHeaderA"); ASSERT_TRUE(value != NULL); EXPECT_EQ(StrCat("response A.", position), *value); value = response->FindHeaderValue("ResponseHeaderB"); ASSERT_TRUE(value != NULL); EXPECT_EQ(StrCat("response B.", position), *value); } MockHttpTransport transport_; }; TEST_F(BatchTestFixture, TestAllOk) { std::vector<BatchTestCase> tests; tests.push_back(BatchTestCase(HttpRequest::GET, 200)); tests.push_back(BatchTestCase(HttpRequest::GET, 200)); tests.push_back(BatchTestCase(HttpRequest::GET, 200)); std::unique_ptr<HttpRequestBatch> batch(MakeBatchRequest(tests, NULL)); EXPECT_EQ("https://www.googleapis.com/batch", batch->http_request().url()); CHECK_EQ(batch->requests().size(), tests.size()); googleapis::util::Status status = batch->Execute(); EXPECT_TRUE(status.ok()) << status.error_message(); CheckResponse(tests, batch->requests()); } TEST_F(BatchTestFixture, TestPartialFailure) { std::vector<BatchTestCase> tests; tests.push_back(BatchTestCase(HttpRequest::GET, 200)); tests.push_back(BatchTestCase(HttpRequest::GET, 400)); tests.push_back(BatchTestCase(HttpRequest::GET, 200)); tests.push_back(BatchTestCase(HttpRequest::GET, 500)); std::unique_ptr<HttpRequestBatch> batch(MakeBatchRequest(tests, NULL)); googleapis::util::Status status = batch->Execute(); EXPECT_TRUE(status.ok()) << status.error_message(); CheckResponse(tests, batch->requests()); } TEST_F(BatchTestFixture, TestWithCredentials) { // Use the repeated and different credentials for different messages. FakeCredential outer_credential("OuterCredential"); FakeCredential override_credential_a("CredentialA"); FakeCredential override_credential_b("CredentialB"); std::vector<BatchTestCase> tests; tests.push_back( BatchTestCase(HttpRequest::GET, 200, &override_credential_a)); tests.push_back(BatchTestCase(HttpRequest::GET, 200, &override_credential_a)); tests.push_back(BatchTestCase(HttpRequest::GET, 200)); tests.push_back(BatchTestCase(HttpRequest::GET, 200, &override_credential_b)); std::unique_ptr<HttpRequestBatch> batch( MakeBatchRequest(tests, &outer_credential)); CHECK_EQ(batch->requests().size(), tests.size()); googleapis::util::Status status = batch->Execute(); EXPECT_TRUE(status.ok()) << status.error_message(); CheckResponse(tests, batch->requests()); } static void DoCallback( int* count, util::error::Code expect_code, HttpRequest* request) { EXPECT_EQ(0, *count) << "id=" << count; EXPECT_EQ(expect_code, request->response()->transport_status().error_code()); ++*count; } TEST_F(BatchTestFixture, TestWithCallback) { std::vector<BatchTestCase> tests; int call_count = 0; HttpRequestCallback* test_callback( NewCallback(&DoCallback, &call_count, util::error::OK)); tests.push_back(BatchTestCase(HttpRequest::GET, 200, NULL, test_callback)); std::unique_ptr<HttpRequestBatch> batch(MakeBatchRequest(tests, NULL)); CHECK_EQ(tests.size(), batch->requests().size()); EXPECT_EQ(0, call_count); googleapis::util::Status status = batch->Execute(); EXPECT_TRUE(status.ok()) << status.error_message(); EXPECT_EQ(1, call_count); CheckResponse(tests, batch->requests()); } TEST_F(BatchTestFixture, TestDeleteWithCallback) { int call_count = 0; std::vector<BatchTestCase> tests; tests.push_back(BatchTestCase(HttpRequest::GET, 200)); tests.push_back(BatchTestCase(HttpRequest::GET, 200)); std::unique_ptr<HttpRequestBatch> batch(MakeBatchRequest(tests, NULL)); HttpRequestCallback* test_callback( NewCallback(&DoCallback, &call_count, util::error::ABORTED)); HttpRequest* to_delete = batch->AddFromGenericRequestAndRetire( new MockHttpRequest(HttpRequest::GET, &transport_), test_callback); CHECK_EQ(tests.size() + 1, batch->requests().size()); EXPECT_EQ(0, call_count); EXPECT_TRUE(batch->RemoveAndDestroyRequest(to_delete).ok()); EXPECT_EQ(1, call_count); CHECK_EQ(tests.size(), batch->requests().size()); googleapis::util::Status status = batch->Execute(); EXPECT_TRUE(status.ok()) << status.error_message(); CheckResponse(tests, batch->requests()); } TEST_F(BatchTestFixture, TestBatchAfterCreation) { std::vector<BatchTestCase> tests; tests.push_back(BatchTestCase(HttpRequest::GET, 200)); tests.push_back(BatchTestCase(HttpRequest::GET, 200)); tests.push_back(BatchTestCase(HttpRequest::GET, 200)); for (int i = 0; i < tests.size(); ++i) { tests[i].create_directly_in_batch = false; } std::unique_ptr<HttpRequestBatch> batch(MakeBatchRequest(tests, NULL)); CHECK_EQ(batch->requests().size(), tests.size()); googleapis::util::Status status = batch->Execute(); EXPECT_TRUE(status.ok()) << status.error_message(); CheckResponse(tests, batch->requests()); } TEST_F(BatchTestFixture, TestMissingAndUnexpectedResponse) { std::vector<BatchTestCase> tests; tests.push_back(BatchTestCase(HttpRequest::GET, 200)); tests.push_back(BatchTestCase(HttpRequest::GET, 400)); tests.push_back(BatchTestCase(HttpRequest::GET, 200)); tests.push_back(BatchTestCase(HttpRequest::GET, 500)); string* mock_response; std::unique_ptr<HttpRequestBatch> batch( MakeBatchRequest(tests, NULL, &mock_response)); string third_result_id = HttpRequestBatch::PointerToHex(batch->requests()[2]); string hacked = StringReplace( *mock_response, third_result_id, "INVALID", true); *mock_response = hacked; googleapis::util::Status status = batch->Execute(); EXPECT_FALSE(status.ok()); EXPECT_EQ(batch->batch_processing_status(), status); EXPECT_TRUE(batch->http_request().response()->ok()); for (int i = 0; i < tests.size(); ++i) { HttpRequest* request = batch->requests()[i]; EXPECT_EQ(i != 2, request->response()->transport_status().ok()) << "i=" << i; if (i == 2) { EXPECT_EQ(0, request->response()->http_code()); } else { EXPECT_EQ(tests[i].http_code, request->response()->http_code()); } } } // Make sure that responses get correlated to the proper request. TEST_F(BatchTestFixture, TestOutOfOrderResponse) { std::vector<BatchTestCase> tests; tests.push_back(BatchTestCase(HttpRequest::GET, 200)); tests.push_back(BatchTestCase(HttpRequest::GET, 200)); tests.push_back(BatchTestCase(HttpRequest::GET, 200)); tests.push_back(BatchTestCase(HttpRequest::GET, 200)); tests.at(1).respond_out_of_order = true; std::unique_ptr<HttpRequestBatch> batch(MakeBatchRequest(tests, NULL)); EXPECT_EQ("https://www.googleapis.com/batch", batch->http_request().url()); CHECK_EQ(batch->requests().size(), tests.size()); googleapis::util::Status status = batch->Execute(); EXPECT_TRUE(status.ok()) << status.error_message(); CheckResponse(tests, batch->requests()); } } // namespace googleapis <file_sep>/service_apis/calendar/google/calendar_api/CMakeLists.txt # This is a CMake file for Calendar API v3 # using the Google APIs Client Library for C++. # # See http://google.github.io/google-api-cpp-client/latest/start/get_started # for more information about what to do with this file. project (google_calendar_api) # These sources assume that the CMakeLists.txt in ../.. added itself to # the include directories so that include paths are specified explicitly # with the directory #include "google/calendar_api/..." add_library(google_calendar_api STATIC acl.cc acl_rule.cc calendar.cc calendar_list.cc calendar_list_entry.cc calendar_notification.cc channel.cc color_definition.cc colors.cc deep_link_data.cc display_info.cc error.cc event.cc event_attachment.cc event_attendee.cc event_date_time.cc event_habit_instance.cc event_reminder.cc events.cc free_busy_calendar.cc free_busy_group.cc free_busy_request.cc free_busy_request_item.cc free_busy_response.cc habit_instance_data.cc launch_info.cc link.cc setting.cc settings.cc time_period.cc calendar_service.cc) target_link_libraries(google_calendar_api googleapis_http) target_link_libraries(google_calendar_api googleapis_internal) target_link_libraries(google_calendar_api googleapis_jsoncpp) target_link_libraries(google_calendar_api googleapis_utils) <file_sep>/service_apis/drive/google/drive_api/channel.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Drive API (drive/v2) // Generated from: // Version: v2 // Revision: 20170512 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_DRIVE_API_CHANNEL_H_ #define GOOGLE_DRIVE_API_CHANNEL_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_drive_api { using namespace googleapis; /** * An notification channel used to watch for resource changes. * * @ingroup DataObject */ class Channel : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static Channel* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Channel(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Channel(Json::Value* storage); /** * Standard destructor. */ virtual ~Channel(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::Channel</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::Channel"); } /** * Determine if the '<code>address</code>' attribute was set. * * @return true if the '<code>address</code>' attribute was set. */ bool has_address() const { return Storage().isMember("address"); } /** * Clears the '<code>address</code>' attribute. */ void clear_address() { MutableStorage()->removeMember("address"); } /** * Get the value of the '<code>address</code>' attribute. */ const StringPiece get_address() const { const Json::Value& v = Storage("address"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>address</code>' attribute. * * The address where notifications are delivered for this channel. * * @param[in] value The new value. */ void set_address(const StringPiece& value) { *MutableStorage("address") = value.data(); } /** * Determine if the '<code>expiration</code>' attribute was set. * * @return true if the '<code>expiration</code>' attribute was set. */ bool has_expiration() const { return Storage().isMember("expiration"); } /** * Clears the '<code>expiration</code>' attribute. */ void clear_expiration() { MutableStorage()->removeMember("expiration"); } /** * Get the value of the '<code>expiration</code>' attribute. */ int64 get_expiration() const { const Json::Value& storage = Storage("expiration"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>expiration</code>' attribute. * * Date and time of notification channel expiration, expressed as a Unix * timestamp, in milliseconds. Optional. * * @param[in] value The new value. */ void set_expiration(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("expiration")); } /** * Determine if the '<code>id</code>' attribute was set. * * @return true if the '<code>id</code>' attribute was set. */ bool has_id() const { return Storage().isMember("id"); } /** * Clears the '<code>id</code>' attribute. */ void clear_id() { MutableStorage()->removeMember("id"); } /** * Get the value of the '<code>id</code>' attribute. */ const StringPiece get_id() const { const Json::Value& v = Storage("id"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>id</code>' attribute. * * A UUID or similar unique string that identifies this channel. * * @param[in] value The new value. */ void set_id(const StringPiece& value) { *MutableStorage("id") = value.data(); } /** * Determine if the '<code>kind</code>' attribute was set. * * @return true if the '<code>kind</code>' attribute was set. */ bool has_kind() const { return Storage().isMember("kind"); } /** * Clears the '<code>kind</code>' attribute. */ void clear_kind() { MutableStorage()->removeMember("kind"); } /** * Get the value of the '<code>kind</code>' attribute. */ const StringPiece get_kind() const { const Json::Value& v = Storage("kind"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kind</code>' attribute. * * Identifies this as a notification channel used to watch for changes to a * resource. Value: the fixed string "api#channel". * * @param[in] value The new value. */ void set_kind(const StringPiece& value) { *MutableStorage("kind") = value.data(); } /** * Determine if the '<code>params</code>' attribute was set. * * @return true if the '<code>params</code>' attribute was set. */ bool has_params() const { return Storage().isMember("params"); } /** * Clears the '<code>params</code>' attribute. */ void clear_params() { MutableStorage()->removeMember("params"); } /** * Get a reference to the value of the '<code>params</code>' attribute. */ const client::JsonCppAssociativeArray<string > get_params() const { const Json::Value& storage = Storage("params"); return client::JsonValueToCppValueHelper<client::JsonCppAssociativeArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>params</code>' property. * * Additional parameters controlling delivery channel behavior. Optional. * * @return The result can be modified to change the attribute value. */ client::JsonCppAssociativeArray<string > mutable_params() { Json::Value* storage = MutableStorage("params"); return client::JsonValueToMutableCppValueHelper<client::JsonCppAssociativeArray<string > >(storage); } /** * Determine if the '<code>payload</code>' attribute was set. * * @return true if the '<code>payload</code>' attribute was set. */ bool has_payload() const { return Storage().isMember("payload"); } /** * Clears the '<code>payload</code>' attribute. */ void clear_payload() { MutableStorage()->removeMember("payload"); } /** * Get the value of the '<code>payload</code>' attribute. */ bool get_payload() const { const Json::Value& storage = Storage("payload"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>payload</code>' attribute. * * A Boolean value to indicate whether payload is wanted. Optional. * * @param[in] value The new value. */ void set_payload(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("payload")); } /** * Determine if the '<code>resourceId</code>' attribute was set. * * @return true if the '<code>resourceId</code>' attribute was set. */ bool has_resource_id() const { return Storage().isMember("resourceId"); } /** * Clears the '<code>resourceId</code>' attribute. */ void clear_resource_id() { MutableStorage()->removeMember("resourceId"); } /** * Get the value of the '<code>resourceId</code>' attribute. */ const StringPiece get_resource_id() const { const Json::Value& v = Storage("resourceId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>resourceId</code>' attribute. * * An opaque ID that identifies the resource being watched on this channel. * Stable across different API versions. * * @param[in] value The new value. */ void set_resource_id(const StringPiece& value) { *MutableStorage("resourceId") = value.data(); } /** * Determine if the '<code>resourceUri</code>' attribute was set. * * @return true if the '<code>resourceUri</code>' attribute was set. */ bool has_resource_uri() const { return Storage().isMember("resourceUri"); } /** * Clears the '<code>resourceUri</code>' attribute. */ void clear_resource_uri() { MutableStorage()->removeMember("resourceUri"); } /** * Get the value of the '<code>resourceUri</code>' attribute. */ const StringPiece get_resource_uri() const { const Json::Value& v = Storage("resourceUri"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>resourceUri</code>' attribute. * * A version-specific identifier for the watched resource. * * @param[in] value The new value. */ void set_resource_uri(const StringPiece& value) { *MutableStorage("resourceUri") = value.data(); } /** * Determine if the '<code>token</code>' attribute was set. * * @return true if the '<code>token</code>' attribute was set. */ bool has_token() const { return Storage().isMember("token"); } /** * Clears the '<code>token</code>' attribute. */ void clear_token() { MutableStorage()->removeMember("token"); } /** * Get the value of the '<code>token</code>' attribute. */ const StringPiece get_token() const { const Json::Value& v = Storage("token"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>token</code>' attribute. * * An arbitrary string delivered to the target address with each notification * delivered over this channel. Optional. * * @param[in] value The new value. */ void set_token(const StringPiece& value) { *MutableStorage("token") = value.data(); } /** * Determine if the '<code>type</code>' attribute was set. * * @return true if the '<code>type</code>' attribute was set. */ bool has_type() const { return Storage().isMember("type"); } /** * Clears the '<code>type</code>' attribute. */ void clear_type() { MutableStorage()->removeMember("type"); } /** * Get the value of the '<code>type</code>' attribute. */ const StringPiece get_type() const { const Json::Value& v = Storage("type"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>type</code>' attribute. * * The type of delivery mechanism used for this channel. * * @param[in] value The new value. */ void set_type(const StringPiece& value) { *MutableStorage("type") = value.data(); } private: void operator=(const Channel&); }; // Channel } // namespace google_drive_api #endif // GOOGLE_DRIVE_API_CHANNEL_H_ <file_sep>/src/googleapis/client/auth/jwt_builder.h /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #ifndef GOOGLEAPIS_AUTH_JWT_BUILDER_H_ #define GOOGLEAPIS_AUTH_JWT_BUILDER_H_ #include <string> using std::string; #include "googleapis/util/status.h" #include <openssl/base.h> namespace googleapis { namespace client { /* * A helper class used to create the JWT we pass to the OAuth2.0 server. * * This class could be broken out into its own module if it is needed elsewhere * or to test more explicitly. */ class JwtBuilder { public: static googleapis::util::Status LoadPrivateKeyFromPkcs12Path( const string& path, string* result_key); static void AppendAsBase64(const char* data, size_t size, string* to); static void AppendAsBase64(const string& from, string* to); static EVP_PKEY* LoadPkeyFromData(const StringPiece data); static EVP_PKEY* LoadPkeyFromP12Path(const char* pkcs12_key_path); static googleapis::util::Status MakeJwtUsingEvp( const string& claims, EVP_PKEY* pkey, string* jwt); }; } // namespace client } // namespace googleapis #endif // GOOGLEAPIS_AUTH_JWT_BUILDER_H_ <file_sep>/service_apis/drive/google/drive_api/comment.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Drive API (drive/v2) // Generated from: // Version: v2 // Revision: 20170512 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_DRIVE_API_COMMENT_H_ #define GOOGLE_DRIVE_API_COMMENT_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/drive_api/comment_reply.h" #include "google/drive_api/user.h" namespace Json { class Value; } // namespace Json namespace google_drive_api { using namespace googleapis; /** * A comment on a file in Google Drive. * * @ingroup DataObject */ class Comment : public client::JsonCppData { public: /** * The context of the file which is being commented on. * * @ingroup DataObject */ class CommentContext : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static CommentContext* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit CommentContext(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit CommentContext(Json::Value* storage); /** * Standard destructor. */ virtual ~CommentContext(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::CommentContext</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::CommentContext"); } /** * Determine if the '<code>type</code>' attribute was set. * * @return true if the '<code>type</code>' attribute was set. */ bool has_type() const { return Storage().isMember("type"); } /** * Clears the '<code>type</code>' attribute. */ void clear_type() { MutableStorage()->removeMember("type"); } /** * Get the value of the '<code>type</code>' attribute. */ const StringPiece get_type() const { const Json::Value& v = Storage("type"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>type</code>' attribute. * * The MIME type of the context snippet. * * @param[in] value The new value. */ void set_type(const StringPiece& value) { *MutableStorage("type") = value.data(); } /** * Determine if the '<code>value</code>' attribute was set. * * @return true if the '<code>value</code>' attribute was set. */ bool has_value() const { return Storage().isMember("value"); } /** * Clears the '<code>value</code>' attribute. */ void clear_value() { MutableStorage()->removeMember("value"); } /** * Get the value of the '<code>value</code>' attribute. */ const StringPiece get_value() const { const Json::Value& v = Storage("value"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>value</code>' attribute. * * Data representation of the segment of the file being commented on. In the * case of a text file for example, this would be the actual text that the * comment is about. * * @param[in] value The new value. */ void set_value(const StringPiece& value) { *MutableStorage("value") = value.data(); } private: void operator=(const CommentContext&); }; // CommentContext /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static Comment* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Comment(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Comment(Json::Value* storage); /** * Standard destructor. */ virtual ~Comment(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::Comment</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::Comment"); } /** * Determine if the '<code>anchor</code>' attribute was set. * * @return true if the '<code>anchor</code>' attribute was set. */ bool has_anchor() const { return Storage().isMember("anchor"); } /** * Clears the '<code>anchor</code>' attribute. */ void clear_anchor() { MutableStorage()->removeMember("anchor"); } /** * Get the value of the '<code>anchor</code>' attribute. */ const StringPiece get_anchor() const { const Json::Value& v = Storage("anchor"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>anchor</code>' attribute. * * A region of the document represented as a JSON string. See anchor * documentation for details on how to define and interpret anchor properties. * * @param[in] value The new value. */ void set_anchor(const StringPiece& value) { *MutableStorage("anchor") = value.data(); } /** * Determine if the '<code>author</code>' attribute was set. * * @return true if the '<code>author</code>' attribute was set. */ bool has_author() const { return Storage().isMember("author"); } /** * Clears the '<code>author</code>' attribute. */ void clear_author() { MutableStorage()->removeMember("author"); } /** * Get a reference to the value of the '<code>author</code>' attribute. */ const User get_author() const; /** * Gets a reference to a mutable value of the '<code>author</code>' property. * * The user who wrote this comment. * * @return The result can be modified to change the attribute value. */ User mutable_author(); /** * Determine if the '<code>commentId</code>' attribute was set. * * @return true if the '<code>commentId</code>' attribute was set. */ bool has_comment_id() const { return Storage().isMember("commentId"); } /** * Clears the '<code>commentId</code>' attribute. */ void clear_comment_id() { MutableStorage()->removeMember("commentId"); } /** * Get the value of the '<code>commentId</code>' attribute. */ const StringPiece get_comment_id() const { const Json::Value& v = Storage("commentId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>commentId</code>' attribute. * * The ID of the comment. * * @param[in] value The new value. */ void set_comment_id(const StringPiece& value) { *MutableStorage("commentId") = value.data(); } /** * Determine if the '<code>content</code>' attribute was set. * * @return true if the '<code>content</code>' attribute was set. */ bool has_content() const { return Storage().isMember("content"); } /** * Clears the '<code>content</code>' attribute. */ void clear_content() { MutableStorage()->removeMember("content"); } /** * Get the value of the '<code>content</code>' attribute. */ const StringPiece get_content() const { const Json::Value& v = Storage("content"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>content</code>' attribute. * * The plain text content used to create this comment. This is not HTML safe * and should only be used as a starting point to make edits to a comment's * content. * * @param[in] value The new value. */ void set_content(const StringPiece& value) { *MutableStorage("content") = value.data(); } /** * Determine if the '<code>context</code>' attribute was set. * * @return true if the '<code>context</code>' attribute was set. */ bool has_context() const { return Storage().isMember("context"); } /** * Clears the '<code>context</code>' attribute. */ void clear_context() { MutableStorage()->removeMember("context"); } /** * Get a reference to the value of the '<code>context</code>' attribute. */ const CommentContext get_context() const { const Json::Value& storage = Storage("context"); return client::JsonValueToCppValueHelper<CommentContext >(storage); } /** * Gets a reference to a mutable value of the '<code>context</code>' property. * * The context of the file which is being commented on. * * @return The result can be modified to change the attribute value. */ CommentContext mutable_context() { Json::Value* storage = MutableStorage("context"); return client::JsonValueToMutableCppValueHelper<CommentContext >(storage); } /** * Determine if the '<code>createdDate</code>' attribute was set. * * @return true if the '<code>createdDate</code>' attribute was set. */ bool has_created_date() const { return Storage().isMember("createdDate"); } /** * Clears the '<code>createdDate</code>' attribute. */ void clear_created_date() { MutableStorage()->removeMember("createdDate"); } /** * Get the value of the '<code>createdDate</code>' attribute. */ client::DateTime get_created_date() const { const Json::Value& storage = Storage("createdDate"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>createdDate</code>' attribute. * * The date when this comment was first created. * * @param[in] value The new value. */ void set_created_date(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("createdDate")); } /** * Determine if the '<code>deleted</code>' attribute was set. * * @return true if the '<code>deleted</code>' attribute was set. */ bool has_deleted() const { return Storage().isMember("deleted"); } /** * Clears the '<code>deleted</code>' attribute. */ void clear_deleted() { MutableStorage()->removeMember("deleted"); } /** * Get the value of the '<code>deleted</code>' attribute. */ bool get_deleted() const { const Json::Value& storage = Storage("deleted"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>deleted</code>' attribute. * * Whether this comment has been deleted. If a comment has been deleted the * content will be cleared and this will only represent a comment that once * existed. * * @param[in] value The new value. */ void set_deleted(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("deleted")); } /** * Determine if the '<code>fileId</code>' attribute was set. * * @return true if the '<code>fileId</code>' attribute was set. */ bool has_file_id() const { return Storage().isMember("fileId"); } /** * Clears the '<code>fileId</code>' attribute. */ void clear_file_id() { MutableStorage()->removeMember("fileId"); } /** * Get the value of the '<code>fileId</code>' attribute. */ const StringPiece get_file_id() const { const Json::Value& v = Storage("fileId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>fileId</code>' attribute. * * The file which this comment is addressing. * * @param[in] value The new value. */ void set_file_id(const StringPiece& value) { *MutableStorage("fileId") = value.data(); } /** * Determine if the '<code>fileTitle</code>' attribute was set. * * @return true if the '<code>fileTitle</code>' attribute was set. */ bool has_file_title() const { return Storage().isMember("fileTitle"); } /** * Clears the '<code>fileTitle</code>' attribute. */ void clear_file_title() { MutableStorage()->removeMember("fileTitle"); } /** * Get the value of the '<code>fileTitle</code>' attribute. */ const StringPiece get_file_title() const { const Json::Value& v = Storage("fileTitle"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>fileTitle</code>' attribute. * * The title of the file which this comment is addressing. * * @param[in] value The new value. */ void set_file_title(const StringPiece& value) { *MutableStorage("fileTitle") = value.data(); } /** * Determine if the '<code>htmlContent</code>' attribute was set. * * @return true if the '<code>htmlContent</code>' attribute was set. */ bool has_html_content() const { return Storage().isMember("htmlContent"); } /** * Clears the '<code>htmlContent</code>' attribute. */ void clear_html_content() { MutableStorage()->removeMember("htmlContent"); } /** * Get the value of the '<code>htmlContent</code>' attribute. */ const StringPiece get_html_content() const { const Json::Value& v = Storage("htmlContent"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>htmlContent</code>' attribute. * * HTML formatted content for this comment. * * @param[in] value The new value. */ void set_html_content(const StringPiece& value) { *MutableStorage("htmlContent") = value.data(); } /** * Determine if the '<code>kind</code>' attribute was set. * * @return true if the '<code>kind</code>' attribute was set. */ bool has_kind() const { return Storage().isMember("kind"); } /** * Clears the '<code>kind</code>' attribute. */ void clear_kind() { MutableStorage()->removeMember("kind"); } /** * Get the value of the '<code>kind</code>' attribute. */ const StringPiece get_kind() const { const Json::Value& v = Storage("kind"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kind</code>' attribute. * * This is always drive#comment. * * @param[in] value The new value. */ void set_kind(const StringPiece& value) { *MutableStorage("kind") = value.data(); } /** * Determine if the '<code>modifiedDate</code>' attribute was set. * * @return true if the '<code>modifiedDate</code>' attribute was set. */ bool has_modified_date() const { return Storage().isMember("modifiedDate"); } /** * Clears the '<code>modifiedDate</code>' attribute. */ void clear_modified_date() { MutableStorage()->removeMember("modifiedDate"); } /** * Get the value of the '<code>modifiedDate</code>' attribute. */ client::DateTime get_modified_date() const { const Json::Value& storage = Storage("modifiedDate"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>modifiedDate</code>' attribute. * * The date when this comment or any of its replies were last modified. * * @param[in] value The new value. */ void set_modified_date(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("modifiedDate")); } /** * Determine if the '<code>replies</code>' attribute was set. * * @return true if the '<code>replies</code>' attribute was set. */ bool has_replies() const { return Storage().isMember("replies"); } /** * Clears the '<code>replies</code>' attribute. */ void clear_replies() { MutableStorage()->removeMember("replies"); } /** * Get a reference to the value of the '<code>replies</code>' attribute. */ const client::JsonCppArray<CommentReply > get_replies() const; /** * Gets a reference to a mutable value of the '<code>replies</code>' property. * * Replies to this post. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<CommentReply > mutable_replies(); /** * Determine if the '<code>selfLink</code>' attribute was set. * * @return true if the '<code>selfLink</code>' attribute was set. */ bool has_self_link() const { return Storage().isMember("selfLink"); } /** * Clears the '<code>selfLink</code>' attribute. */ void clear_self_link() { MutableStorage()->removeMember("selfLink"); } /** * Get the value of the '<code>selfLink</code>' attribute. */ const StringPiece get_self_link() const { const Json::Value& v = Storage("selfLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>selfLink</code>' attribute. * * A link back to this comment. * * @param[in] value The new value. */ void set_self_link(const StringPiece& value) { *MutableStorage("selfLink") = value.data(); } /** * Determine if the '<code>status</code>' attribute was set. * * @return true if the '<code>status</code>' attribute was set. */ bool has_status() const { return Storage().isMember("status"); } /** * Clears the '<code>status</code>' attribute. */ void clear_status() { MutableStorage()->removeMember("status"); } /** * Get the value of the '<code>status</code>' attribute. */ const StringPiece get_status() const { const Json::Value& v = Storage("status"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>status</code>' attribute. * * The status of this comment. Status can be changed by posting a reply to a * comment with the desired status. * <dl> * <dt>"open" * <dd>The comment is still open. * <dt>"resolved" * <dd>The comment has been resolved by one of its replies. * </dl> * * * @param[in] value The new value. */ void set_status(const StringPiece& value) { *MutableStorage("status") = value.data(); } private: void operator=(const Comment&); }; // Comment } // namespace google_drive_api #endif // GOOGLE_DRIVE_API_COMMENT_H_ <file_sep>/service_apis/youtube/google/youtube_api/activity_snippet.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_ACTIVITY_SNIPPET_H_ #define GOOGLE_YOUTUBE_API_ACTIVITY_SNIPPET_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/thumbnail_details.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Basic details about an activity, including title, description, thumbnails, * activity type and group. * * @ingroup DataObject */ class ActivitySnippet : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static ActivitySnippet* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ActivitySnippet(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ActivitySnippet(Json::Value* storage); /** * Standard destructor. */ virtual ~ActivitySnippet(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::ActivitySnippet</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::ActivitySnippet"); } /** * Determine if the '<code>channelId</code>' attribute was set. * * @return true if the '<code>channelId</code>' attribute was set. */ bool has_channel_id() const { return Storage().isMember("channelId"); } /** * Clears the '<code>channelId</code>' attribute. */ void clear_channel_id() { MutableStorage()->removeMember("channelId"); } /** * Get the value of the '<code>channelId</code>' attribute. */ const StringPiece get_channel_id() const { const Json::Value& v = Storage("channelId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>channelId</code>' attribute. * * The ID that YouTube uses to uniquely identify the channel associated with * the activity. * * @param[in] value The new value. */ void set_channel_id(const StringPiece& value) { *MutableStorage("channelId") = value.data(); } /** * Determine if the '<code>channelTitle</code>' attribute was set. * * @return true if the '<code>channelTitle</code>' attribute was set. */ bool has_channel_title() const { return Storage().isMember("channelTitle"); } /** * Clears the '<code>channelTitle</code>' attribute. */ void clear_channel_title() { MutableStorage()->removeMember("channelTitle"); } /** * Get the value of the '<code>channelTitle</code>' attribute. */ const StringPiece get_channel_title() const { const Json::Value& v = Storage("channelTitle"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>channelTitle</code>' attribute. * * Channel title for the channel responsible for this activity. * * @param[in] value The new value. */ void set_channel_title(const StringPiece& value) { *MutableStorage("channelTitle") = value.data(); } /** * Determine if the '<code>description</code>' attribute was set. * * @return true if the '<code>description</code>' attribute was set. */ bool has_description() const { return Storage().isMember("description"); } /** * Clears the '<code>description</code>' attribute. */ void clear_description() { MutableStorage()->removeMember("description"); } /** * Get the value of the '<code>description</code>' attribute. */ const StringPiece get_description() const { const Json::Value& v = Storage("description"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>description</code>' attribute. * * The description of the resource primarily associated with the activity. * * @param[in] value The new value. */ void set_description(const StringPiece& value) { *MutableStorage("description") = value.data(); } /** * Determine if the '<code>groupId</code>' attribute was set. * * @return true if the '<code>groupId</code>' attribute was set. */ bool has_group_id() const { return Storage().isMember("groupId"); } /** * Clears the '<code>groupId</code>' attribute. */ void clear_group_id() { MutableStorage()->removeMember("groupId"); } /** * Get the value of the '<code>groupId</code>' attribute. */ const StringPiece get_group_id() const { const Json::Value& v = Storage("groupId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>groupId</code>' attribute. * * The group ID associated with the activity. A group ID identifies user * events that are associated with the same user and resource. For example, if * a user rates a video and marks the same video as a favorite, the entries * for those events would have the same group ID in the user's activity feed. * In your user interface, you can avoid repetition by grouping events with * the same groupId value. * * @param[in] value The new value. */ void set_group_id(const StringPiece& value) { *MutableStorage("groupId") = value.data(); } /** * Determine if the '<code>publishedAt</code>' attribute was set. * * @return true if the '<code>publishedAt</code>' attribute was set. */ bool has_published_at() const { return Storage().isMember("publishedAt"); } /** * Clears the '<code>publishedAt</code>' attribute. */ void clear_published_at() { MutableStorage()->removeMember("publishedAt"); } /** * Get the value of the '<code>publishedAt</code>' attribute. */ client::DateTime get_published_at() const { const Json::Value& storage = Storage("publishedAt"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>publishedAt</code>' attribute. * * The date and time that the video was uploaded. The value is specified in * ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. * * @param[in] value The new value. */ void set_published_at(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("publishedAt")); } /** * Determine if the '<code>thumbnails</code>' attribute was set. * * @return true if the '<code>thumbnails</code>' attribute was set. */ bool has_thumbnails() const { return Storage().isMember("thumbnails"); } /** * Clears the '<code>thumbnails</code>' attribute. */ void clear_thumbnails() { MutableStorage()->removeMember("thumbnails"); } /** * Get a reference to the value of the '<code>thumbnails</code>' attribute. */ const ThumbnailDetails get_thumbnails() const; /** * Gets a reference to a mutable value of the '<code>thumbnails</code>' * property. * * A map of thumbnail images associated with the resource that is primarily * associated with the activity. For each object in the map, the key is the * name of the thumbnail image, and the value is an object that contains other * information about the thumbnail. * * @return The result can be modified to change the attribute value. */ ThumbnailDetails mutable_thumbnails(); /** * Determine if the '<code>title</code>' attribute was set. * * @return true if the '<code>title</code>' attribute was set. */ bool has_title() const { return Storage().isMember("title"); } /** * Clears the '<code>title</code>' attribute. */ void clear_title() { MutableStorage()->removeMember("title"); } /** * Get the value of the '<code>title</code>' attribute. */ const StringPiece get_title() const { const Json::Value& v = Storage("title"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>title</code>' attribute. * * The title of the resource primarily associated with the activity. * * @param[in] value The new value. */ void set_title(const StringPiece& value) { *MutableStorage("title") = value.data(); } /** * Determine if the '<code>type</code>' attribute was set. * * @return true if the '<code>type</code>' attribute was set. */ bool has_type() const { return Storage().isMember("type"); } /** * Clears the '<code>type</code>' attribute. */ void clear_type() { MutableStorage()->removeMember("type"); } /** * Get the value of the '<code>type</code>' attribute. */ const StringPiece get_type() const { const Json::Value& v = Storage("type"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>type</code>' attribute. * * The type of activity that the resource describes. * * @param[in] value The new value. */ void set_type(const StringPiece& value) { *MutableStorage("type") = value.data(); } private: void operator=(const ActivitySnippet&); }; // ActivitySnippet } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_ACTIVITY_SNIPPET_H_ <file_sep>/service_apis/drive/google/drive_api/about.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Drive API (drive/v2) // Description: // Manages files in Drive including uploading, downloading, searching, detecting changes, and updating sharing permissions. // Classes: // About // Documentation: // https://developers.google.com/drive/ #include "google/drive_api/about.h" #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/drive_api/user.h" #include <string> #include "googleapis/strings/strcat.h" namespace google_drive_api { using namespace googleapis; // Object factory method (static). About::AboutAdditionalRoleInfo::AboutAdditionalRoleInfoRoleSets* About::AboutAdditionalRoleInfo::AboutAdditionalRoleInfoRoleSets::New() { return new client::JsonCppCapsule<AboutAdditionalRoleInfoRoleSets>; } // Standard immutable constructor. About::AboutAdditionalRoleInfo::AboutAdditionalRoleInfoRoleSets::AboutAdditionalRoleInfoRoleSets(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. About::AboutAdditionalRoleInfo::AboutAdditionalRoleInfoRoleSets::AboutAdditionalRoleInfoRoleSets(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. About::AboutAdditionalRoleInfo::AboutAdditionalRoleInfoRoleSets::~AboutAdditionalRoleInfoRoleSets() { } // Properties. // Object factory method (static). About::AboutAdditionalRoleInfo* About::AboutAdditionalRoleInfo::New() { return new client::JsonCppCapsule<AboutAdditionalRoleInfo>; } // Standard immutable constructor. About::AboutAdditionalRoleInfo::AboutAdditionalRoleInfo(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. About::AboutAdditionalRoleInfo::AboutAdditionalRoleInfo(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. About::AboutAdditionalRoleInfo::~AboutAdditionalRoleInfo() { } // Properties. // Object factory method (static). About::AboutExportFormats* About::AboutExportFormats::New() { return new client::JsonCppCapsule<AboutExportFormats>; } // Standard immutable constructor. About::AboutExportFormats::AboutExportFormats(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. About::AboutExportFormats::AboutExportFormats(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. About::AboutExportFormats::~AboutExportFormats() { } // Properties. // Object factory method (static). About::AboutFeatures* About::AboutFeatures::New() { return new client::JsonCppCapsule<AboutFeatures>; } // Standard immutable constructor. About::AboutFeatures::AboutFeatures(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. About::AboutFeatures::AboutFeatures(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. About::AboutFeatures::~AboutFeatures() { } // Properties. // Object factory method (static). About::AboutImportFormats* About::AboutImportFormats::New() { return new client::JsonCppCapsule<AboutImportFormats>; } // Standard immutable constructor. About::AboutImportFormats::AboutImportFormats(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. About::AboutImportFormats::AboutImportFormats(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. About::AboutImportFormats::~AboutImportFormats() { } // Properties. // Object factory method (static). About::AboutMaxUploadSizes* About::AboutMaxUploadSizes::New() { return new client::JsonCppCapsule<AboutMaxUploadSizes>; } // Standard immutable constructor. About::AboutMaxUploadSizes::AboutMaxUploadSizes(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. About::AboutMaxUploadSizes::AboutMaxUploadSizes(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. About::AboutMaxUploadSizes::~AboutMaxUploadSizes() { } // Properties. // Object factory method (static). About::AboutQuotaBytesByService* About::AboutQuotaBytesByService::New() { return new client::JsonCppCapsule<AboutQuotaBytesByService>; } // Standard immutable constructor. About::AboutQuotaBytesByService::AboutQuotaBytesByService(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. About::AboutQuotaBytesByService::AboutQuotaBytesByService(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. About::AboutQuotaBytesByService::~AboutQuotaBytesByService() { } // Properties. // Object factory method (static). About::AboutTeamDriveThemes* About::AboutTeamDriveThemes::New() { return new client::JsonCppCapsule<AboutTeamDriveThemes>; } // Standard immutable constructor. About::AboutTeamDriveThemes::AboutTeamDriveThemes(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. About::AboutTeamDriveThemes::AboutTeamDriveThemes(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. About::AboutTeamDriveThemes::~AboutTeamDriveThemes() { } // Properties. // Object factory method (static). About* About::New() { return new client::JsonCppCapsule<About>; } // Standard immutable constructor. About::About(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. About::About(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. About::~About() { } // Properties. const User About::get_user() const { const Json::Value& storage = Storage("user"); return client::JsonValueToCppValueHelper<User >(storage); } User About::mutable_user() { Json::Value* storage = MutableStorage("user"); return client::JsonValueToMutableCppValueHelper<User >(storage); } } // namespace google_drive_api <file_sep>/service_apis/youtube/google/youtube_api/channel_conversion_ping.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_CHANNEL_CONVERSION_PING_H_ #define GOOGLE_YOUTUBE_API_CHANNEL_CONVERSION_PING_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Pings that the app shall fire (authenticated by biscotti cookie). Each ping * has a context, in which the app must fire the ping, and a url identifying the * ping. * * @ingroup DataObject */ class ChannelConversionPing : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static ChannelConversionPing* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelConversionPing(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelConversionPing(Json::Value* storage); /** * Standard destructor. */ virtual ~ChannelConversionPing(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::ChannelConversionPing</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::ChannelConversionPing"); } /** * Determine if the '<code>context</code>' attribute was set. * * @return true if the '<code>context</code>' attribute was set. */ bool has_context() const { return Storage().isMember("context"); } /** * Clears the '<code>context</code>' attribute. */ void clear_context() { MutableStorage()->removeMember("context"); } /** * Get the value of the '<code>context</code>' attribute. */ const StringPiece get_context() const { const Json::Value& v = Storage("context"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>context</code>' attribute. * * Defines the context of the ping. * * @param[in] value The new value. */ void set_context(const StringPiece& value) { *MutableStorage("context") = value.data(); } /** * Determine if the '<code>conversionUrl</code>' attribute was set. * * @return true if the '<code>conversionUrl</code>' attribute was set. */ bool has_conversion_url() const { return Storage().isMember("conversionUrl"); } /** * Clears the '<code>conversionUrl</code>' attribute. */ void clear_conversion_url() { MutableStorage()->removeMember("conversionUrl"); } /** * Get the value of the '<code>conversionUrl</code>' attribute. */ const StringPiece get_conversion_url() const { const Json::Value& v = Storage("conversionUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>conversionUrl</code>' attribute. * * The url (without the schema) that the player shall send the ping to. It's * at caller's descretion to decide which schema to use (http vs https) * Example of a returned url: //googleads.g.doubleclick.net/pagead/ * viewthroughconversion/962985656/?data=path%3DtHe_path%3Btype%3D * cview%3Butuid%3DGISQtTNGYqaYl4sKxoVvKA=default The caller must append * biscotti authentication (ms param in case of mobile, for example) to this * ping. * * @param[in] value The new value. */ void set_conversion_url(const StringPiece& value) { *MutableStorage("conversionUrl") = value.data(); } private: void operator=(const ChannelConversionPing&); }; // ChannelConversionPing } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_CHANNEL_CONVERSION_PING_H_ <file_sep>/service_apis/youtube/google/youtube_api/live_chat_message_snippet.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_LIVE_CHAT_MESSAGE_SNIPPET_H_ #define GOOGLE_YOUTUBE_API_LIVE_CHAT_MESSAGE_SNIPPET_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/live_chat_fan_funding_event_details.h" #include "google/youtube_api/live_chat_message_deleted_details.h" #include "google/youtube_api/live_chat_message_retracted_details.h" #include "google/youtube_api/live_chat_poll_closed_details.h" #include "google/youtube_api/live_chat_poll_edited_details.h" #include "google/youtube_api/live_chat_poll_opened_details.h" #include "google/youtube_api/live_chat_poll_voted_details.h" #include "google/youtube_api/live_chat_super_chat_details.h" #include "google/youtube_api/live_chat_text_message_details.h" #include "google/youtube_api/live_chat_user_banned_message_details.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * No description provided. * * @ingroup DataObject */ class LiveChatMessageSnippet : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static LiveChatMessageSnippet* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveChatMessageSnippet(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveChatMessageSnippet(Json::Value* storage); /** * Standard destructor. */ virtual ~LiveChatMessageSnippet(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::LiveChatMessageSnippet</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::LiveChatMessageSnippet"); } /** * Determine if the '<code>authorChannelId</code>' attribute was set. * * @return true if the '<code>authorChannelId</code>' attribute was set. */ bool has_author_channel_id() const { return Storage().isMember("authorChannelId"); } /** * Clears the '<code>authorChannelId</code>' attribute. */ void clear_author_channel_id() { MutableStorage()->removeMember("authorChannelId"); } /** * Get the value of the '<code>authorChannelId</code>' attribute. */ const StringPiece get_author_channel_id() const { const Json::Value& v = Storage("authorChannelId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>authorChannelId</code>' attribute. * * The ID of the user that authored this message, this field is not always * filled. textMessageEvent - the user that wrote the message fanFundingEvent * - the user that funded the broadcast newSponsorEvent - the user that just * became a sponsor messageDeletedEvent - the moderator that took the action * messageRetractedEvent - the author that retracted their message * userBannedEvent - the moderator that took the action superChatEvent - the * user that made the purchase. * * @param[in] value The new value. */ void set_author_channel_id(const StringPiece& value) { *MutableStorage("authorChannelId") = value.data(); } /** * Determine if the '<code>displayMessage</code>' attribute was set. * * @return true if the '<code>displayMessage</code>' attribute was set. */ bool has_display_message() const { return Storage().isMember("displayMessage"); } /** * Clears the '<code>displayMessage</code>' attribute. */ void clear_display_message() { MutableStorage()->removeMember("displayMessage"); } /** * Get the value of the '<code>displayMessage</code>' attribute. */ const StringPiece get_display_message() const { const Json::Value& v = Storage("displayMessage"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>displayMessage</code>' attribute. * * Contains a string that can be displayed to the user. If this field is not * present the message is silent, at the moment only messages of type * TOMBSTONE and CHAT_ENDED_EVENT are silent. * * @param[in] value The new value. */ void set_display_message(const StringPiece& value) { *MutableStorage("displayMessage") = value.data(); } /** * Determine if the '<code>fanFundingEventDetails</code>' attribute was set. * * @return true if the '<code>fanFundingEventDetails</code>' attribute was * set. */ bool has_fan_funding_event_details() const { return Storage().isMember("fanFundingEventDetails"); } /** * Clears the '<code>fanFundingEventDetails</code>' attribute. */ void clear_fan_funding_event_details() { MutableStorage()->removeMember("fanFundingEventDetails"); } /** * Get a reference to the value of the '<code>fanFundingEventDetails</code>' * attribute. */ const LiveChatFanFundingEventDetails get_fan_funding_event_details() const; /** * Gets a reference to a mutable value of the * '<code>fanFundingEventDetails</code>' property. * * Details about the funding event, this is only set if the type is * 'fanFundingEvent'. * * @return The result can be modified to change the attribute value. */ LiveChatFanFundingEventDetails mutable_fanFundingEventDetails(); /** * Determine if the '<code>hasDisplayContent</code>' attribute was set. * * @return true if the '<code>hasDisplayContent</code>' attribute was set. */ bool has_has_display_content() const { return Storage().isMember("hasDisplayContent"); } /** * Clears the '<code>hasDisplayContent</code>' attribute. */ void clear_has_display_content() { MutableStorage()->removeMember("hasDisplayContent"); } /** * Get the value of the '<code>hasDisplayContent</code>' attribute. */ bool get_has_display_content() const { const Json::Value& storage = Storage("hasDisplayContent"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>hasDisplayContent</code>' attribute. * * Whether the message has display content that should be displayed to users. * * @param[in] value The new value. */ void set_has_display_content(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("hasDisplayContent")); } /** * Determine if the '<code>liveChatId</code>' attribute was set. * * @return true if the '<code>liveChatId</code>' attribute was set. */ bool has_live_chat_id() const { return Storage().isMember("liveChatId"); } /** * Clears the '<code>liveChatId</code>' attribute. */ void clear_live_chat_id() { MutableStorage()->removeMember("liveChatId"); } /** * Get the value of the '<code>liveChatId</code>' attribute. */ const StringPiece get_live_chat_id() const { const Json::Value& v = Storage("liveChatId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>liveChatId</code>' attribute. * @param[in] value The new value. */ void set_live_chat_id(const StringPiece& value) { *MutableStorage("liveChatId") = value.data(); } /** * Determine if the '<code>messageDeletedDetails</code>' attribute was set. * * @return true if the '<code>messageDeletedDetails</code>' attribute was set. */ bool has_message_deleted_details() const { return Storage().isMember("messageDeletedDetails"); } /** * Clears the '<code>messageDeletedDetails</code>' attribute. */ void clear_message_deleted_details() { MutableStorage()->removeMember("messageDeletedDetails"); } /** * Get a reference to the value of the '<code>messageDeletedDetails</code>' * attribute. */ const LiveChatMessageDeletedDetails get_message_deleted_details() const; /** * Gets a reference to a mutable value of the * '<code>messageDeletedDetails</code>' property. * @return The result can be modified to change the attribute value. */ LiveChatMessageDeletedDetails mutable_messageDeletedDetails(); /** * Determine if the '<code>messageRetractedDetails</code>' attribute was set. * * @return true if the '<code>messageRetractedDetails</code>' attribute was * set. */ bool has_message_retracted_details() const { return Storage().isMember("messageRetractedDetails"); } /** * Clears the '<code>messageRetractedDetails</code>' attribute. */ void clear_message_retracted_details() { MutableStorage()->removeMember("messageRetractedDetails"); } /** * Get a reference to the value of the '<code>messageRetractedDetails</code>' * attribute. */ const LiveChatMessageRetractedDetails get_message_retracted_details() const; /** * Gets a reference to a mutable value of the * '<code>messageRetractedDetails</code>' property. * @return The result can be modified to change the attribute value. */ LiveChatMessageRetractedDetails mutable_messageRetractedDetails(); /** * Determine if the '<code>pollClosedDetails</code>' attribute was set. * * @return true if the '<code>pollClosedDetails</code>' attribute was set. */ bool has_poll_closed_details() const { return Storage().isMember("pollClosedDetails"); } /** * Clears the '<code>pollClosedDetails</code>' attribute. */ void clear_poll_closed_details() { MutableStorage()->removeMember("pollClosedDetails"); } /** * Get a reference to the value of the '<code>pollClosedDetails</code>' * attribute. */ const LiveChatPollClosedDetails get_poll_closed_details() const; /** * Gets a reference to a mutable value of the '<code>pollClosedDetails</code>' * property. * @return The result can be modified to change the attribute value. */ LiveChatPollClosedDetails mutable_pollClosedDetails(); /** * Determine if the '<code>pollEditedDetails</code>' attribute was set. * * @return true if the '<code>pollEditedDetails</code>' attribute was set. */ bool has_poll_edited_details() const { return Storage().isMember("pollEditedDetails"); } /** * Clears the '<code>pollEditedDetails</code>' attribute. */ void clear_poll_edited_details() { MutableStorage()->removeMember("pollEditedDetails"); } /** * Get a reference to the value of the '<code>pollEditedDetails</code>' * attribute. */ const LiveChatPollEditedDetails get_poll_edited_details() const; /** * Gets a reference to a mutable value of the '<code>pollEditedDetails</code>' * property. * @return The result can be modified to change the attribute value. */ LiveChatPollEditedDetails mutable_pollEditedDetails(); /** * Determine if the '<code>pollOpenedDetails</code>' attribute was set. * * @return true if the '<code>pollOpenedDetails</code>' attribute was set. */ bool has_poll_opened_details() const { return Storage().isMember("pollOpenedDetails"); } /** * Clears the '<code>pollOpenedDetails</code>' attribute. */ void clear_poll_opened_details() { MutableStorage()->removeMember("pollOpenedDetails"); } /** * Get a reference to the value of the '<code>pollOpenedDetails</code>' * attribute. */ const LiveChatPollOpenedDetails get_poll_opened_details() const; /** * Gets a reference to a mutable value of the '<code>pollOpenedDetails</code>' * property. * @return The result can be modified to change the attribute value. */ LiveChatPollOpenedDetails mutable_pollOpenedDetails(); /** * Determine if the '<code>pollVotedDetails</code>' attribute was set. * * @return true if the '<code>pollVotedDetails</code>' attribute was set. */ bool has_poll_voted_details() const { return Storage().isMember("pollVotedDetails"); } /** * Clears the '<code>pollVotedDetails</code>' attribute. */ void clear_poll_voted_details() { MutableStorage()->removeMember("pollVotedDetails"); } /** * Get a reference to the value of the '<code>pollVotedDetails</code>' * attribute. */ const LiveChatPollVotedDetails get_poll_voted_details() const; /** * Gets a reference to a mutable value of the '<code>pollVotedDetails</code>' * property. * @return The result can be modified to change the attribute value. */ LiveChatPollVotedDetails mutable_pollVotedDetails(); /** * Determine if the '<code>publishedAt</code>' attribute was set. * * @return true if the '<code>publishedAt</code>' attribute was set. */ bool has_published_at() const { return Storage().isMember("publishedAt"); } /** * Clears the '<code>publishedAt</code>' attribute. */ void clear_published_at() { MutableStorage()->removeMember("publishedAt"); } /** * Get the value of the '<code>publishedAt</code>' attribute. */ client::DateTime get_published_at() const { const Json::Value& storage = Storage("publishedAt"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>publishedAt</code>' attribute. * * The date and time when the message was orignally published. The value is * specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. * * @param[in] value The new value. */ void set_published_at(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("publishedAt")); } /** * Determine if the '<code>superChatDetails</code>' attribute was set. * * @return true if the '<code>superChatDetails</code>' attribute was set. */ bool has_super_chat_details() const { return Storage().isMember("superChatDetails"); } /** * Clears the '<code>superChatDetails</code>' attribute. */ void clear_super_chat_details() { MutableStorage()->removeMember("superChatDetails"); } /** * Get a reference to the value of the '<code>superChatDetails</code>' * attribute. */ const LiveChatSuperChatDetails get_super_chat_details() const; /** * Gets a reference to a mutable value of the '<code>superChatDetails</code>' * property. * * Details about the Super Chat event, this is only set if the type is * 'superChatEvent'. * * @return The result can be modified to change the attribute value. */ LiveChatSuperChatDetails mutable_superChatDetails(); /** * Determine if the '<code>textMessageDetails</code>' attribute was set. * * @return true if the '<code>textMessageDetails</code>' attribute was set. */ bool has_text_message_details() const { return Storage().isMember("textMessageDetails"); } /** * Clears the '<code>textMessageDetails</code>' attribute. */ void clear_text_message_details() { MutableStorage()->removeMember("textMessageDetails"); } /** * Get a reference to the value of the '<code>textMessageDetails</code>' * attribute. */ const LiveChatTextMessageDetails get_text_message_details() const; /** * Gets a reference to a mutable value of the * '<code>textMessageDetails</code>' property. * * Details about the text message, this is only set if the type is * 'textMessageEvent'. * * @return The result can be modified to change the attribute value. */ LiveChatTextMessageDetails mutable_textMessageDetails(); /** * Determine if the '<code>type</code>' attribute was set. * * @return true if the '<code>type</code>' attribute was set. */ bool has_type() const { return Storage().isMember("type"); } /** * Clears the '<code>type</code>' attribute. */ void clear_type() { MutableStorage()->removeMember("type"); } /** * Get the value of the '<code>type</code>' attribute. */ const StringPiece get_type() const { const Json::Value& v = Storage("type"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>type</code>' attribute. * * The type of message, this will always be present, it determines the * contents of the message as well as which fields will be present. * * @param[in] value The new value. */ void set_type(const StringPiece& value) { *MutableStorage("type") = value.data(); } /** * Determine if the '<code>userBannedDetails</code>' attribute was set. * * @return true if the '<code>userBannedDetails</code>' attribute was set. */ bool has_user_banned_details() const { return Storage().isMember("userBannedDetails"); } /** * Clears the '<code>userBannedDetails</code>' attribute. */ void clear_user_banned_details() { MutableStorage()->removeMember("userBannedDetails"); } /** * Get a reference to the value of the '<code>userBannedDetails</code>' * attribute. */ const LiveChatUserBannedMessageDetails get_user_banned_details() const; /** * Gets a reference to a mutable value of the '<code>userBannedDetails</code>' * property. * @return The result can be modified to change the attribute value. */ LiveChatUserBannedMessageDetails mutable_userBannedDetails(); private: void operator=(const LiveChatMessageSnippet&); }; // LiveChatMessageSnippet } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_LIVE_CHAT_MESSAGE_SNIPPET_H_ <file_sep>/src/samples/command_processor_test.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <string> using std::string; #include <vector> #include "samples/command_processor.h" #include <gtest/gtest.h> namespace googleapis { using sample::CommandProcessor; TEST(Test, SplitArgs) { std::vector<string> list; EXPECT_TRUE(CommandProcessor::SplitArgs(" a b ", &list)); EXPECT_EQ(2, list.size()); EXPECT_EQ("a", list[0]); EXPECT_EQ("b", list[1]); list.clear(); EXPECT_TRUE(CommandProcessor::SplitArgs(" \"a b\" ", &list)); EXPECT_EQ(1, list.size()); EXPECT_EQ("a b", list[0]); list.clear(); EXPECT_TRUE(CommandProcessor::SplitArgs("a\\\" b", &list)); EXPECT_EQ(2, list.size()); EXPECT_EQ("a\"", list[0]); EXPECT_EQ("b", list[1]); list.clear(); EXPECT_TRUE(CommandProcessor::SplitArgs("\\ a\\ b\\\\ c", &list)); EXPECT_EQ(3, list.size()); EXPECT_EQ(" ", list[0]); EXPECT_EQ("a b\\", list[1]); EXPECT_EQ("c", list[2]); list.clear(); EXPECT_FALSE(CommandProcessor::SplitArgs("\"a b", &list)); EXPECT_EQ(1, list.size()); EXPECT_EQ("a b", list[0]); list.clear(); EXPECT_FALSE(CommandProcessor::SplitArgs("a b\\", &list)); EXPECT_EQ(2, list.size()); EXPECT_EQ("a", list[0]); EXPECT_EQ("b", list[1]); } } // namespace googleapis <file_sep>/service_apis/youtube/google/youtube_api/channel_statistics.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_CHANNEL_STATISTICS_H_ #define GOOGLE_YOUTUBE_API_CHANNEL_STATISTICS_H_ #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Statistics about a channel: number of subscribers, number of videos in the * channel, etc. * * @ingroup DataObject */ class ChannelStatistics : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static ChannelStatistics* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelStatistics(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ChannelStatistics(Json::Value* storage); /** * Standard destructor. */ virtual ~ChannelStatistics(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::ChannelStatistics</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::ChannelStatistics"); } /** * Determine if the '<code>commentCount</code>' attribute was set. * * @return true if the '<code>commentCount</code>' attribute was set. */ bool has_comment_count() const { return Storage().isMember("commentCount"); } /** * Clears the '<code>commentCount</code>' attribute. */ void clear_comment_count() { MutableStorage()->removeMember("commentCount"); } /** * Get the value of the '<code>commentCount</code>' attribute. */ uint64 get_comment_count() const { const Json::Value& storage = Storage("commentCount"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>commentCount</code>' attribute. * * The number of comments for the channel. * * @param[in] value The new value. */ void set_comment_count(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("commentCount")); } /** * Determine if the '<code>hiddenSubscriberCount</code>' attribute was set. * * @return true if the '<code>hiddenSubscriberCount</code>' attribute was set. */ bool has_hidden_subscriber_count() const { return Storage().isMember("hiddenSubscriberCount"); } /** * Clears the '<code>hiddenSubscriberCount</code>' attribute. */ void clear_hidden_subscriber_count() { MutableStorage()->removeMember("hiddenSubscriberCount"); } /** * Get the value of the '<code>hiddenSubscriberCount</code>' attribute. */ bool get_hidden_subscriber_count() const { const Json::Value& storage = Storage("hiddenSubscriberCount"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>hiddenSubscriberCount</code>' attribute. * * Whether or not the number of subscribers is shown for this user. * * @param[in] value The new value. */ void set_hidden_subscriber_count(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("hiddenSubscriberCount")); } /** * Determine if the '<code>subscriberCount</code>' attribute was set. * * @return true if the '<code>subscriberCount</code>' attribute was set. */ bool has_subscriber_count() const { return Storage().isMember("subscriberCount"); } /** * Clears the '<code>subscriberCount</code>' attribute. */ void clear_subscriber_count() { MutableStorage()->removeMember("subscriberCount"); } /** * Get the value of the '<code>subscriberCount</code>' attribute. */ uint64 get_subscriber_count() const { const Json::Value& storage = Storage("subscriberCount"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>subscriberCount</code>' attribute. * * The number of subscribers that the channel has. * * @param[in] value The new value. */ void set_subscriber_count(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("subscriberCount")); } /** * Determine if the '<code>videoCount</code>' attribute was set. * * @return true if the '<code>videoCount</code>' attribute was set. */ bool has_video_count() const { return Storage().isMember("videoCount"); } /** * Clears the '<code>videoCount</code>' attribute. */ void clear_video_count() { MutableStorage()->removeMember("videoCount"); } /** * Get the value of the '<code>videoCount</code>' attribute. */ uint64 get_video_count() const { const Json::Value& storage = Storage("videoCount"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>videoCount</code>' attribute. * * The number of videos uploaded to the channel. * * @param[in] value The new value. */ void set_video_count(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("videoCount")); } /** * Determine if the '<code>viewCount</code>' attribute was set. * * @return true if the '<code>viewCount</code>' attribute was set. */ bool has_view_count() const { return Storage().isMember("viewCount"); } /** * Clears the '<code>viewCount</code>' attribute. */ void clear_view_count() { MutableStorage()->removeMember("viewCount"); } /** * Get the value of the '<code>viewCount</code>' attribute. */ uint64 get_view_count() const { const Json::Value& storage = Storage("viewCount"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>viewCount</code>' attribute. * * The number of times the channel has been viewed. * * @param[in] value The new value. */ void set_view_count(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("viewCount")); } private: void operator=(const ChannelStatistics&); }; // ChannelStatistics } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_CHANNEL_STATISTICS_H_ <file_sep>/src/samples/abstract_login_flow.h /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #ifndef GOOGLEAPIS_SAMPLES_ABSTRACT_LOGIN_FLOW_H_ #define GOOGLEAPIS_SAMPLES_ABSTRACT_LOGIN_FLOW_H_ #include <string> using std::string; #include "googleapis/client/util/abstract_webserver.h" #include "googleapis/client/util/status.h" #include "googleapis/base/callback.h" #include "googleapis/base/macros.h" namespace googleapis { namespace client { class OAuth2AuthorizationFlow; class OAuth2Credential; } // namespace client namespace sample { using client::AbstractWebServer; using client::WebServerRequest; /* * Component that manages obtaining credentials for user http sessions. * @ingroup Samples * * This class is just for experimenting and illustrative purposes. * It is an abstract base class providing an interface and control flow * for managing credentials within login/logout commands on a webserver. * * I'm not sure how much sense it makes but seems convienent for playing * with different mechanisms and supporting samples. This is not tied * to a user, only "active" cookie and credential. Presumably the cookie * maps into some application level user object that also manages the * credential and this is just abstracting a process flow independent of that. * * The class is thread-safe for managing concurrent login flows for different * users. * * To use this class you must subclass it and override a few methods to render * pages as you wish and to make credentials available to your application. * <ul> * <li>DoReceiveCredentialForCookieId to pass the credentials received * from the OAuth2 server up to your application. * * <li>DoGetCredentialForCookieId to get access to credentials from your * application so the flow can make decisions. * * <li>DoRespondWithWelcomPage to display a page when credentials are * obtained without a redirect for the page that requested them. * This means you've logged in from the login page directly as opposed * to passing through the login page on your way to protected content. * * <li>DoRespondWithNotLoggedInPage to display the login page when * credentials are not available and there is no redirect. At the * minimum this page should contain a control that, when clicked, * will call InitiateAuthorizationFlow. Note that when there is * a redirect there is a redirect the page will pass through to the * OAuth2.0 server to obtain credentials and log in. * * <li>DoRespondWithLoginErrorPage to display the login page when * a login attempt fails (or is canceled). * </ul> * * * Additionally you must make the following calls to set this up: * <ul> * <li>AddLoginUrl to hook the login processing into your webserver if you * want the component to perform the login flow. * * <li>AddLogoutUrl to hook the logout processing into your webserver if you * want the component to perform the logout flow. * * <li>AddReceiveAccessTokenUrl to hook up the OAuth2 token callback and * receive credentials from the server. * </ul> * * Finally, call InitiateAuthorizationFlow to initiate a flow. * This is usualy from an action on the page returned by * DoRespondWithLoginPage. */ class AbstractLoginFlow { public: /* * Standard constructor. * * @param[in] cookie_name The name of the cookie to use for the cookie_id. * @param[in] redirect_name The name of the redirect query parameter. * @param[in] flow The flow for talking to the OAuth 2.0 server when we * need to exchange an authorization code for access token. */ AbstractLoginFlow( const string& cookie_name, const string& redirect_name, client::OAuth2AuthorizationFlow* flow); /* * Standard destructor. */ virtual ~AbstractLoginFlow(); googleapis::util::Status InitiateAuthorizationFlow( WebServerRequest* request, const string& redirect_url = ""); /* * Return the cookie_id cooke bound in the constructor. */ const string& cookie_name() const { return cookie_name_; } /* * Return the redirect url parameter bound in the constructor. */ const string& redirect_param_name() const { return redirect_name_; } /* * Return the OAuth2 Authorization flow bound in the constructor. */ client::OAuth2AuthorizationFlow* flow() const { return flow_; } /* * Adds a login handler with the given URL to the web server. * * @param[in] url The url that triggers the handler. * @param[ni] httpd The webserver to register then handler on. * * @see DoRespondWithWelcomePage * @see DoRespondWithNotLoggedInPage * @see DoRespondWithLoginErrorPage */ void AddLoginUrl(const string& url, AbstractWebServer* httpd); /* * Adds a logout handler with the given URL to the web server. * * @param[in] url The url that triggers the handler. * @param[ni] httpd The webserver to register then handler on. */ void AddLogoutUrl(const string& url, AbstractWebServer* httpd); /* * Adds the handler receiving OAuth2 access tokens using the given URL. * * @param[in] url The url that triggers the handler. * @param[ni] httpd The webserver to register then handler on. */ void AddReceiveAccessTokenUrl( const string& url, AbstractWebServer* httpd); protected: /* * Handler called when the component receives a login credential * (or failure). * * This should just update application state. The resopnse will be handled * elsewhere. * * @param[in] cookie_id The user cookie this notification is for. * @param[in] status Ok if we have a credential, otherwise the error. * @parma[in] credential Ownership is passed (NULL on failure). * * @return true if this cookie was known already, false if first time. */ virtual bool DoReceiveCredentialForCookieId( const string& cookie_id, const googleapis::util::Status& status, client::OAuth2Credential* credential) = 0; /* * Returns the current credential for the given cookie_id * * @param[in] cookie_id The cookie id from the cookie. * * @return NULL if no credential is available. */ virtual client::OAuth2Credential* DoGetCredentialForCookieId(const string& cookie_id) = 0; virtual googleapis::util::Status DoInitiateAuthorizationFlow( WebServerRequest* request, const string& redirect_url) = 0; /* * Handler after we've successfully logged in without a redirect. * * The default implementation fails. You must override this if you * add the login url handler. * * @param[in] cookie_id The user cookie that logged in. * @param[in] requset_data The request we are responding to. * * @return ok or reason for failure. * * @see AddLoginUrl */ virtual googleapis::util::Status DoRespondWithWelcomePage( const string& cookie_id, WebServerRequest* request) = 0; /* * Handler for login page when we are not logged in and have no redirect. * * The default implementation fails. You must override this if you * add the login url handler. * * @param[in] cookie_id The cookie for the user that is not logged in. * @param[in] requset_data The request we are responding to. * * @return ok or reason for failure. */ virtual googleapis::util::Status DoRespondWithNotLoggedInPage( const string& cookie_id, WebServerRequest* request) = 0; /* * Handler for login page when we encounter a login error. * * The default implementation fails. You must override this if you * add the login url handler. * * @param[in] cookie_id The cookie for the user that is not logged in. * @param[in] requset_data The request we are responding to. * * @return ok or reason for failure. */ virtual googleapis::util::Status DoRespondWithLoginErrorPage( const string& cookie_id, const googleapis::util::Status& status, WebServerRequest* request) = 0; virtual googleapis::util::Status DoHandleAccessTokenUrl(WebServerRequest* request); virtual googleapis::util::Status DoHandleLoginUrl(WebServerRequest* request); virtual googleapis::util::Status DoHandleLogoutUrl(WebServerRequest* request); protected: /* * Responds to a request by redirecting to a url. * * @param[in] url The url we want to redirect to. * @param[in] cookie_id The cookie_id to write into a cookie. * @param[in] request The request we're responding to. * * @return ok or reason for failure. */ googleapis::util::Status RedirectToUrl( const string& url, const string& cookie_id, WebServerRequest* request); googleapis::util::Status ReceiveAuthorizationCode( const string& cookie_id, const string& want_url, WebServerRequest* request); /* * Extracts the user id from the cookie in the request * * @return empty string if there is no cookie. */ string GetCookieId(WebServerRequest* request); const string& login_url() const { return login_url_; } const string& logout_url() const { return logout_url_; } const string& access_token_url() const { return access_token_url_; } private: /* * The name of the cookie we're using for the cookie_id value. */ string cookie_name_; string redirect_name_; string login_url_; string logout_url_; string access_token_url_; /* * A reference to the flow that we're using to get Authorization Tokens. * We do not own this. */ client::OAuth2AuthorizationFlow* flow_; /* * This callback is used to resolve the requests from the OAuth 2.0 server * that gives us the authentication codes (or responses) that we asked for. */ googleapis::util::Status HandleAccessTokenUrl(WebServerRequest* request); /* * This callback implements the login process flow added by AddLoginUrl */ googleapis::util::Status HandleLoginUrl(WebServerRequest* request); /* * This callback implements the logout process flow added by AddLogoutUrl */ googleapis::util::Status HandleLogoutUrl(WebServerRequest* request); DISALLOW_COPY_AND_ASSIGN(AbstractLoginFlow); }; } // namespace sample } // namespace googleapis #endif // GOOGLEAPIS_SAMPLES_ABSTRACT_LOGIN_FLOW_H_ <file_sep>/src/samples/installed_application.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <iostream> using std::cout; using std::endl; using std::ostream; // NOLINT #include "googleapis/config.h" #include "samples/installed_application.h" #include "googleapis/client/auth/file_credential_store.h" #include "googleapis/client/auth/oauth2_authorization.h" #ifdef googleapis_HAVE_OPENSSL #include "googleapis/client/data/openssl_codec.h" #endif #include "googleapis/client/transport/curl_http_transport.h" #include "googleapis/client/transport/http_transport.h" #include "googleapis/client/util/mongoose_webserver.h" #include "googleapis/client/util/status.h" #include <glog/logging.h> #include "googleapis/strings/strcat.h" namespace googleapis { using std::endl; using std::istream; using std::ostream; using client::CredentialStore; using client::FileCredentialStoreFactory; using client::MongooseWebServer; using client::OAuth2AuthorizationFlow; using client::OAuth2ClientSpec; using client::OAuth2Credential; using client::OAuth2RequestOptions; #ifdef googleapis_HAVE_OPENSSL using client::OpenSslCodecFactory; #endif using client::StatusCanceled; using client::StatusInvalidArgument; using client::StatusOk; using client::StatusUnknown; using client::WebServerAuthorizationCodeGetter; static googleapis::util::Status PromptShellForAuthorizationCode( OAuth2AuthorizationFlow* flow, const client::OAuth2RequestOptions& options, string* authorization_code) { // TODO(user): Normally one would not get from the commandline, // rather you would do something interactive within their browser/display. string url = flow->GenerateAuthorizationCodeRequestUrlWithOptions(options); std::cout << "Enter the following url into a browser:\n" << url << std::endl; std::cout << "Enter the browser's response: "; authorization_code->clear(); std::cin >> *authorization_code; if (authorization_code->empty()) { return StatusCanceled("Canceled"); } else { return StatusOk(); } } static googleapis::util::Status ValidateUserName(const string& name) { if (name.find("/") != string::npos) { return StatusInvalidArgument("UserNames cannot contain '/'"); } else if (name == "." || name == "..") { return StatusInvalidArgument( StrCat("'", name, "' is not a valid user name")); } return StatusOk(); } namespace sample { InstalledApplication::InstalledApplication(const string& name) : name_(name) , user_name_(""), revoke_on_exit_(false) { config_.reset(new client::HttpTransportLayerConfig); client::HttpTransportFactory* factory = new client::CurlHttpTransportFactory(config_.get()); config_->ResetDefaultTransportFactory(factory); } InstalledApplication::~InstalledApplication() { if (revoke_on_exit_) { VLOG(1) << "Revoking access on exit"; googleapis::util::Status status = flow_->PerformRevokeToken(true, credential_.get()); if (!status.ok()) { LOG(ERROR) << "Error revoking access token: " << status.error_message(); } } } util::Status InstalledApplication::ChangeUser(const string& user_name) { if (user_name != user_name_) { string proposed_name = user_name; googleapis::util::Status status = ValidateUserName(proposed_name); if (!status.ok()) return status; credential_.reset(NULL); // Use the application name instead of its client_id if (!status.ok()) { string error = StrCat(status.ToString(), ": Could not change to username=", proposed_name, ". You are no longer an authorized user.\n"); LOG(WARNING) << error; return StatusUnknown(error); } user_name_ = proposed_name; std::cout << "Changed to username=" << user_name_ << endl; } return StatusOk(); } OAuth2Credential* InstalledApplication::credential() { if (!credential_.get()) { credential_.reset(flow_->NewCredential()); } return credential_.get(); } void InstalledApplication::ResetCredential( OAuth2Credential* credential) { VLOG(1) << "Resetting credential"; credential_.reset(credential); } util::Status InstalledApplication::InitHelper() { return StatusOk(); } util::Status InstalledApplication::Init(const string& secrets_path) { googleapis::util::Status status; HttpTransport* transport = config_->NewDefaultTransport(&status); if (!transport) { return status; } flow_.reset(OAuth2AuthorizationFlow::MakeFlowFromClientSecretsPath( secrets_path, transport, &status)); if (!status.ok()) { return status; } // A derived class can always change this again later after init if it has // an embedded server to redirect to. flow_->mutable_client_spec()->set_redirect_uri( OAuth2AuthorizationFlow::kOutOfBandUrl); flow_->set_authorization_code_callback( NewPermanentCallback(&PromptShellForAuthorizationCode, flow_.get())); flow_->set_check_email(true); #ifdef googleapis_HAVE_OPENSSL OpenSslCodecFactory* openssl_factory = new OpenSslCodecFactory; status = openssl_factory->SetPassphrase( flow_->client_spec().client_secret()); if (status.ok()) { string home_path; status = FileCredentialStoreFactory::GetSystemHomeDirectoryStorePath( &home_path); if (status.ok()) { FileCredentialStoreFactory store_factory(home_path); store_factory.set_codec_factory(openssl_factory); flow_->ResetCredentialStore( store_factory.NewCredentialStore(name_, &status)); } } if (!status.ok()) { LOG(ERROR) << "Could not use credential store: " << status.error_message() << endl; } #endif status = InitHelper(); if (!status.ok()) { delete flow_.release(); } return status; } util::Status InstalledApplication::AuthorizeClient() { OAuth2RequestOptions options; options.scopes = OAuth2AuthorizationFlow::JoinScopes(default_oauth2_scopes()); options.email = user_name_; googleapis::util::Status status = flow_->RefreshCredentialWithOptions(options, credential()); if (!status.ok()) { std::cout << status.error_message() << endl; } return status; } util::Status InstalledApplication::RevokeClient() { return flow_->PerformRevokeToken(true, credential_.get()); } util::Status InstalledApplication::StartupHttpd( int port, const string& path, WebServerAuthorizationCodeGetter::AskCallback* asker) { if (path.at(0) != '/') { return StatusInvalidArgument( StrCat("Path must be absolute. got path=", path)); } if (port <= 0) { return StatusInvalidArgument(StrCat("Invalid port=", port)); } httpd_.reset(new MongooseWebServer(port)); authorization_code_getter_.reset( new WebServerAuthorizationCodeGetter(asker)); authorization_code_getter_->AddReceiveAuthorizationCodeUrlPath( path, httpd_.get()); googleapis::util::Status status = httpd_->Startup(); if (status.ok()) { // Change the flow so that it uses a browser and httpd server. flow_->mutable_client_spec()->set_redirect_uri( httpd_->MakeEndpointUrl(true, path)); flow_->set_authorization_code_callback( NewPermanentCallback( authorization_code_getter_.get(), &WebServerAuthorizationCodeGetter::PromptForAuthorizationCode, flow_.get())); } return status; } void InstalledApplication::ShutdownHttpd() { if (httpd_.get()) { httpd_->Shutdown(); httpd_.reset(NULL); } if (authorization_code_getter_.get()) { delete authorization_code_getter_.release(); // Change the flow so that it uses the shell. flow_->mutable_client_spec()->set_redirect_uri( OAuth2AuthorizationFlow::kOutOfBandUrl); flow_->set_authorization_code_callback( NewPermanentCallback(&PromptShellForAuthorizationCode, flow_.get())); } } } // namespace sample } // namespace googleapis <file_sep>/service_apis/youtube/google/youtube_api/video_snippet.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_VIDEO_SNIPPET_H_ #define GOOGLE_YOUTUBE_API_VIDEO_SNIPPET_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/thumbnail_details.h" #include "google/youtube_api/video_localization.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Basic details about a video, including title, description, uploader, * thumbnails and category. * * @ingroup DataObject */ class VideoSnippet : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static VideoSnippet* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoSnippet(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoSnippet(Json::Value* storage); /** * Standard destructor. */ virtual ~VideoSnippet(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::VideoSnippet</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::VideoSnippet"); } /** * Determine if the '<code>categoryId</code>' attribute was set. * * @return true if the '<code>categoryId</code>' attribute was set. */ bool has_category_id() const { return Storage().isMember("categoryId"); } /** * Clears the '<code>categoryId</code>' attribute. */ void clear_category_id() { MutableStorage()->removeMember("categoryId"); } /** * Get the value of the '<code>categoryId</code>' attribute. */ const StringPiece get_category_id() const { const Json::Value& v = Storage("categoryId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>categoryId</code>' attribute. * * The YouTube video category associated with the video. * * @param[in] value The new value. */ void set_category_id(const StringPiece& value) { *MutableStorage("categoryId") = value.data(); } /** * Determine if the '<code>channelId</code>' attribute was set. * * @return true if the '<code>channelId</code>' attribute was set. */ bool has_channel_id() const { return Storage().isMember("channelId"); } /** * Clears the '<code>channelId</code>' attribute. */ void clear_channel_id() { MutableStorage()->removeMember("channelId"); } /** * Get the value of the '<code>channelId</code>' attribute. */ const StringPiece get_channel_id() const { const Json::Value& v = Storage("channelId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>channelId</code>' attribute. * * The ID that YouTube uses to uniquely identify the channel that the video * was uploaded to. * * @param[in] value The new value. */ void set_channel_id(const StringPiece& value) { *MutableStorage("channelId") = value.data(); } /** * Determine if the '<code>channelTitle</code>' attribute was set. * * @return true if the '<code>channelTitle</code>' attribute was set. */ bool has_channel_title() const { return Storage().isMember("channelTitle"); } /** * Clears the '<code>channelTitle</code>' attribute. */ void clear_channel_title() { MutableStorage()->removeMember("channelTitle"); } /** * Get the value of the '<code>channelTitle</code>' attribute. */ const StringPiece get_channel_title() const { const Json::Value& v = Storage("channelTitle"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>channelTitle</code>' attribute. * * Channel title for the channel that the video belongs to. * * @param[in] value The new value. */ void set_channel_title(const StringPiece& value) { *MutableStorage("channelTitle") = value.data(); } /** * Determine if the '<code>defaultAudioLanguage</code>' attribute was set. * * @return true if the '<code>defaultAudioLanguage</code>' attribute was set. */ bool has_default_audio_language() const { return Storage().isMember("defaultAudioLanguage"); } /** * Clears the '<code>defaultAudioLanguage</code>' attribute. */ void clear_default_audio_language() { MutableStorage()->removeMember("defaultAudioLanguage"); } /** * Get the value of the '<code>defaultAudioLanguage</code>' attribute. */ const StringPiece get_default_audio_language() const { const Json::Value& v = Storage("defaultAudioLanguage"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>defaultAudioLanguage</code>' attribute. * * The default_audio_language property specifies the language spoken in the * video's default audio track. * * @param[in] value The new value. */ void set_default_audio_language(const StringPiece& value) { *MutableStorage("defaultAudioLanguage") = value.data(); } /** * Determine if the '<code>defaultLanguage</code>' attribute was set. * * @return true if the '<code>defaultLanguage</code>' attribute was set. */ bool has_default_language() const { return Storage().isMember("defaultLanguage"); } /** * Clears the '<code>defaultLanguage</code>' attribute. */ void clear_default_language() { MutableStorage()->removeMember("defaultLanguage"); } /** * Get the value of the '<code>defaultLanguage</code>' attribute. */ const StringPiece get_default_language() const { const Json::Value& v = Storage("defaultLanguage"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>defaultLanguage</code>' attribute. * * The language of the videos's default snippet. * * @param[in] value The new value. */ void set_default_language(const StringPiece& value) { *MutableStorage("defaultLanguage") = value.data(); } /** * Determine if the '<code>description</code>' attribute was set. * * @return true if the '<code>description</code>' attribute was set. */ bool has_description() const { return Storage().isMember("description"); } /** * Clears the '<code>description</code>' attribute. */ void clear_description() { MutableStorage()->removeMember("description"); } /** * Get the value of the '<code>description</code>' attribute. */ const StringPiece get_description() const { const Json::Value& v = Storage("description"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>description</code>' attribute. * * The video's description. * * @param[in] value The new value. */ void set_description(const StringPiece& value) { *MutableStorage("description") = value.data(); } /** * Determine if the '<code>liveBroadcastContent</code>' attribute was set. * * @return true if the '<code>liveBroadcastContent</code>' attribute was set. */ bool has_live_broadcast_content() const { return Storage().isMember("liveBroadcastContent"); } /** * Clears the '<code>liveBroadcastContent</code>' attribute. */ void clear_live_broadcast_content() { MutableStorage()->removeMember("liveBroadcastContent"); } /** * Get the value of the '<code>liveBroadcastContent</code>' attribute. */ const StringPiece get_live_broadcast_content() const { const Json::Value& v = Storage("liveBroadcastContent"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>liveBroadcastContent</code>' attribute. * * Indicates if the video is an upcoming/active live broadcast. Or it's "none" * if the video is not an upcoming/active live broadcast. * * @param[in] value The new value. */ void set_live_broadcast_content(const StringPiece& value) { *MutableStorage("liveBroadcastContent") = value.data(); } /** * Determine if the '<code>localized</code>' attribute was set. * * @return true if the '<code>localized</code>' attribute was set. */ bool has_localized() const { return Storage().isMember("localized"); } /** * Clears the '<code>localized</code>' attribute. */ void clear_localized() { MutableStorage()->removeMember("localized"); } /** * Get a reference to the value of the '<code>localized</code>' attribute. */ const VideoLocalization get_localized() const; /** * Gets a reference to a mutable value of the '<code>localized</code>' * property. * * Localized snippet selected with the hl parameter. If no such localization * exists, this field is populated with the default snippet. (Read-only). * * @return The result can be modified to change the attribute value. */ VideoLocalization mutable_localized(); /** * Determine if the '<code>publishedAt</code>' attribute was set. * * @return true if the '<code>publishedAt</code>' attribute was set. */ bool has_published_at() const { return Storage().isMember("publishedAt"); } /** * Clears the '<code>publishedAt</code>' attribute. */ void clear_published_at() { MutableStorage()->removeMember("publishedAt"); } /** * Get the value of the '<code>publishedAt</code>' attribute. */ client::DateTime get_published_at() const { const Json::Value& storage = Storage("publishedAt"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>publishedAt</code>' attribute. * * The date and time that the video was uploaded. The value is specified in * ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. * * @param[in] value The new value. */ void set_published_at(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("publishedAt")); } /** * Determine if the '<code>tags</code>' attribute was set. * * @return true if the '<code>tags</code>' attribute was set. */ bool has_tags() const { return Storage().isMember("tags"); } /** * Clears the '<code>tags</code>' attribute. */ void clear_tags() { MutableStorage()->removeMember("tags"); } /** * Get a reference to the value of the '<code>tags</code>' attribute. */ const client::JsonCppArray<string > get_tags() const { const Json::Value& storage = Storage("tags"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>tags</code>' property. * * A list of keyword tags associated with the video. Tags may contain spaces. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_tags() { Json::Value* storage = MutableStorage("tags"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>thumbnails</code>' attribute was set. * * @return true if the '<code>thumbnails</code>' attribute was set. */ bool has_thumbnails() const { return Storage().isMember("thumbnails"); } /** * Clears the '<code>thumbnails</code>' attribute. */ void clear_thumbnails() { MutableStorage()->removeMember("thumbnails"); } /** * Get a reference to the value of the '<code>thumbnails</code>' attribute. */ const ThumbnailDetails get_thumbnails() const; /** * Gets a reference to a mutable value of the '<code>thumbnails</code>' * property. * * A map of thumbnail images associated with the video. For each object in the * map, the key is the name of the thumbnail image, and the value is an object * that contains other information about the thumbnail. * * @return The result can be modified to change the attribute value. */ ThumbnailDetails mutable_thumbnails(); /** * Determine if the '<code>title</code>' attribute was set. * * @return true if the '<code>title</code>' attribute was set. */ bool has_title() const { return Storage().isMember("title"); } /** * Clears the '<code>title</code>' attribute. */ void clear_title() { MutableStorage()->removeMember("title"); } /** * Get the value of the '<code>title</code>' attribute. */ const StringPiece get_title() const { const Json::Value& v = Storage("title"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>title</code>' attribute. * * The video's title. * * @param[in] value The new value. */ void set_title(const StringPiece& value) { *MutableStorage("title") = value.data(); } private: void operator=(const VideoSnippet&); }; // VideoSnippet } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_VIDEO_SNIPPET_H_ <file_sep>/service_apis/youtube/google/youtube_api/watch_settings.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_WATCH_SETTINGS_H_ #define GOOGLE_YOUTUBE_API_WATCH_SETTINGS_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Branding properties for the watch. All deprecated. * * @ingroup DataObject */ class WatchSettings : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static WatchSettings* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit WatchSettings(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit WatchSettings(Json::Value* storage); /** * Standard destructor. */ virtual ~WatchSettings(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::WatchSettings</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::WatchSettings"); } /** * Determine if the '<code>backgroundColor</code>' attribute was set. * * @return true if the '<code>backgroundColor</code>' attribute was set. */ bool has_background_color() const { return Storage().isMember("backgroundColor"); } /** * Clears the '<code>backgroundColor</code>' attribute. */ void clear_background_color() { MutableStorage()->removeMember("backgroundColor"); } /** * Get the value of the '<code>backgroundColor</code>' attribute. */ const StringPiece get_background_color() const { const Json::Value& v = Storage("backgroundColor"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>backgroundColor</code>' attribute. * * The text color for the video watch page's branded area. * * @param[in] value The new value. */ void set_background_color(const StringPiece& value) { *MutableStorage("backgroundColor") = value.data(); } /** * Determine if the '<code>featuredPlaylistId</code>' attribute was set. * * @return true if the '<code>featuredPlaylistId</code>' attribute was set. */ bool has_featured_playlist_id() const { return Storage().isMember("featuredPlaylistId"); } /** * Clears the '<code>featuredPlaylistId</code>' attribute. */ void clear_featured_playlist_id() { MutableStorage()->removeMember("featuredPlaylistId"); } /** * Get the value of the '<code>featuredPlaylistId</code>' attribute. */ const StringPiece get_featured_playlist_id() const { const Json::Value& v = Storage("featuredPlaylistId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>featuredPlaylistId</code>' attribute. * * An ID that uniquely identifies a playlist that displays next to the video * player. * * @param[in] value The new value. */ void set_featured_playlist_id(const StringPiece& value) { *MutableStorage("featuredPlaylistId") = value.data(); } /** * Determine if the '<code>textColor</code>' attribute was set. * * @return true if the '<code>textColor</code>' attribute was set. */ bool has_text_color() const { return Storage().isMember("textColor"); } /** * Clears the '<code>textColor</code>' attribute. */ void clear_text_color() { MutableStorage()->removeMember("textColor"); } /** * Get the value of the '<code>textColor</code>' attribute. */ const StringPiece get_text_color() const { const Json::Value& v = Storage("textColor"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>textColor</code>' attribute. * * The background color for the video watch page's branded area. * * @param[in] value The new value. */ void set_text_color(const StringPiece& value) { *MutableStorage("textColor") = value.data(); } private: void operator=(const WatchSettings&); }; // WatchSettings } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_WATCH_SETTINGS_H_ <file_sep>/service_apis/youtube/google/youtube_api/image_settings.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Description: // Supports core YouTube features, such as uploading videos, creating and managing playlists, searching for content, and much more. // Classes: // ImageSettings // Documentation: // https://developers.google.com/youtube/v3 #include "google/youtube_api/image_settings.h" #include <string> #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/localized_property.h" #include <string> #include "googleapis/strings/strcat.h" namespace google_youtube_api { using namespace googleapis; // Object factory method (static). ImageSettings* ImageSettings::New() { return new client::JsonCppCapsule<ImageSettings>; } // Standard immutable constructor. ImageSettings::ImageSettings(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. ImageSettings::ImageSettings(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. ImageSettings::~ImageSettings() { } // Properties. const LocalizedProperty ImageSettings::get_background_image_url() const { const Json::Value& storage = Storage("backgroundImageUrl"); return client::JsonValueToCppValueHelper<LocalizedProperty >(storage); } LocalizedProperty ImageSettings::mutable_backgroundImageUrl() { Json::Value* storage = MutableStorage("backgroundImageUrl"); return client::JsonValueToMutableCppValueHelper<LocalizedProperty >(storage); } const LocalizedProperty ImageSettings::get_large_branded_banner_image_imap_script() const { const Json::Value& storage = Storage("largeBrandedBannerImageImapScript"); return client::JsonValueToCppValueHelper<LocalizedProperty >(storage); } LocalizedProperty ImageSettings::mutable_largeBrandedBannerImageImapScript() { Json::Value* storage = MutableStorage("largeBrandedBannerImageImapScript"); return client::JsonValueToMutableCppValueHelper<LocalizedProperty >(storage); } const LocalizedProperty ImageSettings::get_large_branded_banner_image_url() const { const Json::Value& storage = Storage("largeBrandedBannerImageUrl"); return client::JsonValueToCppValueHelper<LocalizedProperty >(storage); } LocalizedProperty ImageSettings::mutable_largeBrandedBannerImageUrl() { Json::Value* storage = MutableStorage("largeBrandedBannerImageUrl"); return client::JsonValueToMutableCppValueHelper<LocalizedProperty >(storage); } const LocalizedProperty ImageSettings::get_small_branded_banner_image_imap_script() const { const Json::Value& storage = Storage("smallBrandedBannerImageImapScript"); return client::JsonValueToCppValueHelper<LocalizedProperty >(storage); } LocalizedProperty ImageSettings::mutable_smallBrandedBannerImageImapScript() { Json::Value* storage = MutableStorage("smallBrandedBannerImageImapScript"); return client::JsonValueToMutableCppValueHelper<LocalizedProperty >(storage); } const LocalizedProperty ImageSettings::get_small_branded_banner_image_url() const { const Json::Value& storage = Storage("smallBrandedBannerImageUrl"); return client::JsonValueToCppValueHelper<LocalizedProperty >(storage); } LocalizedProperty ImageSettings::mutable_smallBrandedBannerImageUrl() { Json::Value* storage = MutableStorage("smallBrandedBannerImageUrl"); return client::JsonValueToMutableCppValueHelper<LocalizedProperty >(storage); } } // namespace google_youtube_api <file_sep>/service_apis/youtube/google/youtube_api/live_stream.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Description: // Supports core YouTube features, such as uploading videos, creating and managing playlists, searching for content, and much more. // Classes: // LiveStream // Documentation: // https://developers.google.com/youtube/v3 #include "google/youtube_api/live_stream.h" #include <string> #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/cdn_settings.h" #include "google/youtube_api/live_stream_content_details.h" #include "google/youtube_api/live_stream_snippet.h" #include "google/youtube_api/live_stream_status.h" #include <string> #include "googleapis/strings/strcat.h" namespace google_youtube_api { using namespace googleapis; // Object factory method (static). LiveStream* LiveStream::New() { return new client::JsonCppCapsule<LiveStream>; } // Standard immutable constructor. LiveStream::LiveStream(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. LiveStream::LiveStream(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. LiveStream::~LiveStream() { } // Properties. const CdnSettings LiveStream::get_cdn() const { const Json::Value& storage = Storage("cdn"); return client::JsonValueToCppValueHelper<CdnSettings >(storage); } CdnSettings LiveStream::mutable_cdn() { Json::Value* storage = MutableStorage("cdn"); return client::JsonValueToMutableCppValueHelper<CdnSettings >(storage); } const LiveStreamContentDetails LiveStream::get_content_details() const { const Json::Value& storage = Storage("contentDetails"); return client::JsonValueToCppValueHelper<LiveStreamContentDetails >(storage); } LiveStreamContentDetails LiveStream::mutable_contentDetails() { Json::Value* storage = MutableStorage("contentDetails"); return client::JsonValueToMutableCppValueHelper<LiveStreamContentDetails >(storage); } const LiveStreamSnippet LiveStream::get_snippet() const { const Json::Value& storage = Storage("snippet"); return client::JsonValueToCppValueHelper<LiveStreamSnippet >(storage); } LiveStreamSnippet LiveStream::mutable_snippet() { Json::Value* storage = MutableStorage("snippet"); return client::JsonValueToMutableCppValueHelper<LiveStreamSnippet >(storage); } const LiveStreamStatus LiveStream::get_status() const { const Json::Value& storage = Storage("status"); return client::JsonValueToCppValueHelper<LiveStreamStatus >(storage); } LiveStreamStatus LiveStream::mutable_status() { Json::Value* storage = MutableStorage("status"); return client::JsonValueToMutableCppValueHelper<LiveStreamStatus >(storage); } } // namespace google_youtube_api <file_sep>/service_apis/drive/google/drive_api/drive_service.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // //------------------------------------------------------------------------------ // This code was generated by google-apis-code-generator 1.5.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. //------------------------------------------------------------------------------ #ifndef GOOGLE_DRIVE_API_DRIVE_SERVICE_H_ #define GOOGLE_DRIVE_API_DRIVE_SERVICE_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/service/client_service.h" #include "googleapis/client/service/media_uploader.h" #include "googleapis/client/service/service_request_pager.h" #include "googleapis/client/util/status.h" #include "googleapis/client/util/uri_template.h" #include "google/drive_api/about.h" #include "google/drive_api/app.h" #include "google/drive_api/app_list.h" #include "google/drive_api/change.h" #include "google/drive_api/change_list.h" #include "google/drive_api/channel.h" #include "google/drive_api/child_list.h" #include "google/drive_api/child_reference.h" #include "google/drive_api/comment.h" #include "google/drive_api/comment_list.h" #include "google/drive_api/comment_reply.h" #include "google/drive_api/comment_reply_list.h" #include "google/drive_api/file.h" #include "google/drive_api/file_list.h" #include "google/drive_api/generated_ids.h" #include "google/drive_api/parent_list.h" #include "google/drive_api/parent_reference.h" #include "google/drive_api/permission.h" #include "google/drive_api/permission_id.h" #include "google/drive_api/permission_list.h" #include "google/drive_api/property.h" #include "google/drive_api/property_list.h" #include "google/drive_api/revision.h" #include "google/drive_api/revision_list.h" #include "google/drive_api/start_page_token.h" #include "google/drive_api/team_drive.h" #include "google/drive_api/team_drive_list.h" namespace google_drive_api { using namespace googleapis; /** * \mainpage * Drive API Version v2 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/drive/'>Drive API</a> * <tr><th>API Version<td>v2 * <tr><th>API Rev<td>20170512 * <tr><th>API Docs * <td><a href='https://developers.google.com/drive/'> * https://developers.google.com/drive/</a> * <tr><th>Discovery Name<td>drive * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Drive API can be found at * <a href='https://developers.google.com/drive/'>https://developers.google.com/drive/</a>. * * For more information about the Google APIs Client Library for C++, see * <a href='https://developers.google.com/api-client-library/cpp/start/get_started'> * https://developers.google.com/api-client-library/cpp/start/get_started</a> */ class DriveService; /** * Implements a common base method for all methods within the DriveService. * * This class defines all the attributes common across all methods. * It does not pertain to any specific service API so is not normally * explicitly instantiated. */ class DriveServiceBaseRequest : public client::ClientServiceRequest { public: /** * Standard constructor. * * @param[in] service The service instance to send to when executed. * In practice this will be supplied internally by the service * when it acts as a method factory. * * @param[in] credential If not NULL then the credential to authorize with. * In practice this is supplied by the user code that is creating * the method instance. * * @param[in] method The HTTP method to use for the underlying HTTP request. * In practice this is specified by the particular API endpoint and * supplied internally by the derived class for that endpoint. * * @param[in] uri_template The <a href='http://tools.ietf.org/html/rfc6570'> * RFC 6570 URI Template</a> specifying the url to invoke * The parameters in the template should be resolvable attributes. * In practice this parameter is supplied internally by the derived * class for the endpoint. */ DriveServiceBaseRequest( const client::ClientService* service, client::AuthorizationCredential* credential, client::HttpRequest::HttpMethod method, const StringPiece& uri_template); /** * Standard destructor. */ virtual ~DriveServiceBaseRequest(); /** * Clears the '<code>alt</code>' attribute so it is no longer set. */ void clear_alt() { _have_alt_ = false; client::ClearCppValueHelper(&alt_); } /** * Gets the optional '<code>alt</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_alt() const { return alt_; } /** * Gets a modifiable pointer to the optional <code>alt</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_alt() { _have_alt_ = true; return &alt_; } /** * Sets the '<code>alt</code>' attribute. * * @param[in] value Data format for the response. */ void set_alt(const string& value) { _have_alt_ = true; alt_ = value; } /** * Clears the '<code>fields</code>' attribute so it is no longer set. */ void clear_fields() { _have_fields_ = false; client::ClearCppValueHelper(&fields_); } /** * Gets the optional '<code>fields</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_fields() const { return fields_; } /** * Gets a modifiable pointer to the optional <code>fields</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_fields() { _have_fields_ = true; return &fields_; } /** * Sets the '<code>fields</code>' attribute. * * @param[in] value Selector specifying which fields to include in a partial * response. */ void set_fields(const string& value) { _have_fields_ = true; fields_ = value; } /** * Clears the '<code>key</code>' attribute so it is no longer set. */ void clear_key() { _have_key_ = false; client::ClearCppValueHelper(&key_); } /** * Gets the optional '<code>key</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_key() const { return key_; } /** * Gets a modifiable pointer to the optional <code>key</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_key() { _have_key_ = true; return &key_; } /** * Sets the '<code>key</code>' attribute. * * @param[in] value API key. Your API key identifies your project and provides * you with API access, quota, and reports. Required unless you provide an * OAuth 2.0 token. */ void set_key(const string& value) { _have_key_ = true; key_ = value; } /** * Clears the '<code>oauth_token</code>' attribute so it is no longer set. */ void clear_oauth_token() { _have_oauth_token_ = false; client::ClearCppValueHelper(&oauth_token_); } /** * Gets the optional '<code>oauth_token</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_oauth_token() const { return oauth_token_; } /** * Gets a modifiable pointer to the optional <code>oauth_token</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_oauthToken() { _have_oauth_token_ = true; return &oauth_token_; } /** * Sets the '<code>oauth_token</code>' attribute. * * @param[in] value OAuth 2.0 token for the current user. */ void set_oauth_token(const string& value) { _have_oauth_token_ = true; oauth_token_ = value; } /** * Clears the '<code>prettyPrint</code>' attribute so it is no longer set. */ void clear_pretty_print() { _have_pretty_print_ = false; client::ClearCppValueHelper(&pretty_print_); } /** * Gets the optional '<code>prettyPrint</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_pretty_print() const { return pretty_print_; } /** * Sets the '<code>prettyPrint</code>' attribute. * * @param[in] value Returns response with indentations and line breaks. */ void set_pretty_print(bool value) { _have_pretty_print_ = true; pretty_print_ = value; } /** * Clears the '<code>quotaUser</code>' attribute so it is no longer set. */ void clear_quota_user() { _have_quota_user_ = false; client::ClearCppValueHelper(&quota_user_); } /** * Gets the optional '<code>quotaUser</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_quota_user() const { return quota_user_; } /** * Gets a modifiable pointer to the optional <code>quotaUser</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_quotaUser() { _have_quota_user_ = true; return &quota_user_; } /** * Sets the '<code>quotaUser</code>' attribute. * * @param[in] value Available to use for quota purposes for server-side * applications. Can be any arbitrary string assigned to a user, but should * not exceed 40 characters. Overrides userIp if both are provided. */ void set_quota_user(const string& value) { _have_quota_user_ = true; quota_user_ = value; } /** * Clears the '<code>userIp</code>' attribute so it is no longer set. */ void clear_user_ip() { _have_user_ip_ = false; client::ClearCppValueHelper(&user_ip_); } /** * Gets the optional '<code>userIp</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_user_ip() const { return user_ip_; } /** * Gets a modifiable pointer to the optional <code>userIp</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_userIp() { _have_user_ip_ = true; return &user_ip_; } /** * Sets the '<code>userIp</code>' attribute. * * @param[in] value IP address of the site where the request originates. Use * this if you want to enforce per-user limits. */ void set_user_ip(const string& value) { _have_user_ip_ = true; user_ip_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the * URI supplied to the constructor. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); protected: /** * Prepares the method's HTTP request to send body content as JSON. * * Only to be used for method constructors. */ void AddJsonContentToRequest(const client::JsonCppData *content); private: string alt_; string fields_; string key_; string oauth_token_; bool pretty_print_; string quota_user_; string user_ip_; bool _have_alt_ : 1; bool _have_fields_ : 1; bool _have_key_ : 1; bool _have_oauth_token_ : 1; bool _have_pretty_print_ : 1; bool _have_quota_user_ : 1; bool _have_user_ip_ : 1; DISALLOW_COPY_AND_ASSIGN(DriveServiceBaseRequest); }; /** * Implements the get method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class AboutResource_GetMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. */ AboutResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_); /** * Standard destructor. */ virtual ~AboutResource_GetMethod(); /** * Clears the '<code>includeSubscribed</code>' attribute so it is no longer * set. */ void clear_include_subscribed() { _have_include_subscribed_ = false; client::ClearCppValueHelper(&include_subscribed_); } /** * Gets the optional '<code>includeSubscribed</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_include_subscribed() const { return include_subscribed_; } /** * Sets the '<code>includeSubscribed</code>' attribute. * * @param[in] value When calculating the number of remaining change IDs, * whether to include public files the user has opened and shared files. * When set to false, this counts only change IDs for owned files and any * shared or public files that the user has explicitly added to a folder * they own. */ void set_include_subscribed(bool value) { _have_include_subscribed_ = true; include_subscribed_ = value; } /** * Clears the '<code>maxChangeIdCount</code>' attribute so it is no longer * set. */ void clear_max_change_id_count() { _have_max_change_id_count_ = false; client::ClearCppValueHelper(&max_change_id_count_); } /** * Gets the optional '<code>maxChangeIdCount</code>' attribute. * * If the value is not set then the default value will be returned. */ int64 get_max_change_id_count() const { return max_change_id_count_; } /** * Sets the '<code>maxChangeIdCount</code>' attribute. * * @param[in] value Maximum number of remaining change IDs to count. */ void set_max_change_id_count(int64 value) { _have_max_change_id_count_ = true; max_change_id_count_ = value; } /** * Clears the '<code>startChangeId</code>' attribute so it is no longer set. */ void clear_start_change_id() { _have_start_change_id_ = false; client::ClearCppValueHelper(&start_change_id_); } /** * Gets the optional '<code>startChangeId</code>' attribute. * * If the value is not set then the default value will be returned. */ int64 get_start_change_id() const { return start_change_id_; } /** * Sets the '<code>startChangeId</code>' attribute. * * @param[in] value Change ID to start counting from when calculating number * of remaining change IDs. */ void set_start_change_id(int64 value) { _have_start_change_id_ = true; start_change_id_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( About* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: bool include_subscribed_; int64 max_change_id_count_; int64 start_change_id_; bool _have_include_subscribed_ : 1; bool _have_max_change_id_count_ : 1; bool _have_start_change_id_ : 1; DISALLOW_COPY_AND_ASSIGN(AboutResource_GetMethod); }; /** * Implements the get method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.apps.readonly * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.readonly */ class AppsResource_GetMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] app_id The ID of the app. */ AppsResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& app_id); /** * Standard destructor. */ virtual ~AppsResource_GetMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( App* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string app_id_; DISALLOW_COPY_AND_ASSIGN(AppsResource_GetMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive.apps.readonly */ class AppsResource_ListMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. */ AppsResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_); /** * Standard destructor. */ virtual ~AppsResource_ListMethod(); /** * Clears the '<code>appFilterExtensions</code>' attribute so it is no * longer set. */ void clear_app_filter_extensions() { _have_app_filter_extensions_ = false; client::ClearCppValueHelper(&app_filter_extensions_); } /** * Gets the optional '<code>appFilterExtensions</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_app_filter_extensions() const { return app_filter_extensions_; } /** * Gets a modifiable pointer to the optional * <code>appFilterExtensions</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_appFilterExtensions() { _have_app_filter_extensions_ = true; return &app_filter_extensions_; } /** * Sets the '<code>appFilterExtensions</code>' attribute. * * @param[in] value A comma-separated list of file extensions for open with * filtering. All apps within the given app query scope which can open any * of the given file extensions will be included in the response. If * appFilterMimeTypes are provided as well, the result is a union of the two * resulting app lists. */ void set_app_filter_extensions(const string& value) { _have_app_filter_extensions_ = true; app_filter_extensions_ = value; } /** * Clears the '<code>appFilterMimeTypes</code>' attribute so it is no longer * set. */ void clear_app_filter_mime_types() { _have_app_filter_mime_types_ = false; client::ClearCppValueHelper(&app_filter_mime_types_); } /** * Gets the optional '<code>appFilterMimeTypes</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_app_filter_mime_types() const { return app_filter_mime_types_; } /** * Gets a modifiable pointer to the optional * <code>appFilterMimeTypes</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_appFilterMimeTypes() { _have_app_filter_mime_types_ = true; return &app_filter_mime_types_; } /** * Sets the '<code>appFilterMimeTypes</code>' attribute. * * @param[in] value A comma-separated list of MIME types for open with * filtering. All apps within the given app query scope which can open any * of the given MIME types will be included in the response. If * appFilterExtensions are provided as well, the result is a union of the * two resulting app lists. */ void set_app_filter_mime_types(const string& value) { _have_app_filter_mime_types_ = true; app_filter_mime_types_ = value; } /** * Clears the '<code>languageCode</code>' attribute so it is no longer set. */ void clear_language_code() { _have_language_code_ = false; client::ClearCppValueHelper(&language_code_); } /** * Gets the optional '<code>languageCode</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_language_code() const { return language_code_; } /** * Gets a modifiable pointer to the optional <code>languageCode</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_languageCode() { _have_language_code_ = true; return &language_code_; } /** * Sets the '<code>languageCode</code>' attribute. * * @param[in] value A language or locale code, as defined by BCP 47, with * some extensions from Unicode's LDML format * (http://www.unicode.org/reports/tr35/). */ void set_language_code(const string& value) { _have_language_code_ = true; language_code_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( AppList* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string app_filter_extensions_; string app_filter_mime_types_; string language_code_; bool _have_app_filter_extensions_ : 1; bool _have_app_filter_mime_types_ : 1; bool _have_language_code_ : 1; DISALLOW_COPY_AND_ASSIGN(AppsResource_ListMethod); }; /** * Implements the get method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.apps.readonly * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class ChangesResource_GetMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] change_id The ID of the change. */ ChangesResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& change_id); /** * Standard destructor. */ virtual ~ChangesResource_GetMethod(); /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Clears the '<code>teamDriveId</code>' attribute so it is no longer set. */ void clear_team_drive_id() { _have_team_drive_id_ = false; client::ClearCppValueHelper(&team_drive_id_); } /** * Gets the optional '<code>teamDriveId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_team_drive_id() const { return team_drive_id_; } /** * Gets a modifiable pointer to the optional <code>teamDriveId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_teamDriveId() { _have_team_drive_id_ = true; return &team_drive_id_; } /** * Sets the '<code>teamDriveId</code>' attribute. * * @param[in] value The Team Drive from which the change will be returned. */ void set_team_drive_id(const string& value) { _have_team_drive_id_ = true; team_drive_id_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Change* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string change_id_; bool supports_team_drives_; string team_drive_id_; bool _have_supports_team_drives_ : 1; bool _have_team_drive_id_ : 1; DISALLOW_COPY_AND_ASSIGN(ChangesResource_GetMethod); }; /** * Implements the getStartPageToken method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.apps.readonly * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class ChangesResource_GetStartPageTokenMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. */ ChangesResource_GetStartPageTokenMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_); /** * Standard destructor. */ virtual ~ChangesResource_GetStartPageTokenMethod(); /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Clears the '<code>teamDriveId</code>' attribute so it is no longer set. */ void clear_team_drive_id() { _have_team_drive_id_ = false; client::ClearCppValueHelper(&team_drive_id_); } /** * Gets the optional '<code>teamDriveId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_team_drive_id() const { return team_drive_id_; } /** * Gets a modifiable pointer to the optional <code>teamDriveId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_teamDriveId() { _have_team_drive_id_ = true; return &team_drive_id_; } /** * Sets the '<code>teamDriveId</code>' attribute. * * @param[in] value The ID of the Team Drive for which the starting * pageToken for listing future changes from that Team Drive will be * returned. */ void set_team_drive_id(const string& value) { _have_team_drive_id_ = true; team_drive_id_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( StartPageToken* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: bool supports_team_drives_; string team_drive_id_; bool _have_supports_team_drives_ : 1; bool _have_team_drive_id_ : 1; DISALLOW_COPY_AND_ASSIGN(ChangesResource_GetStartPageTokenMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.apps.readonly * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class ChangesResource_ListMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. */ ChangesResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_); /** * Standard destructor. */ virtual ~ChangesResource_ListMethod(); /** * Clears the '<code>includeCorpusRemovals</code>' attribute so it is no * longer set. */ void clear_include_corpus_removals() { _have_include_corpus_removals_ = false; client::ClearCppValueHelper(&include_corpus_removals_); } /** * Gets the optional '<code>includeCorpusRemovals</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_include_corpus_removals() const { return include_corpus_removals_; } /** * Sets the '<code>includeCorpusRemovals</code>' attribute. * * @param[in] value Whether changes should include the file resource if the * file is still accessible by the user at the time of the request, even * when a file was removed from the list of changes and there will be no * further change entries for this file. */ void set_include_corpus_removals(bool value) { _have_include_corpus_removals_ = true; include_corpus_removals_ = value; } /** * Clears the '<code>includeDeleted</code>' attribute so it is no longer * set. */ void clear_include_deleted() { _have_include_deleted_ = false; client::ClearCppValueHelper(&include_deleted_); } /** * Gets the optional '<code>includeDeleted</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_include_deleted() const { return include_deleted_; } /** * Sets the '<code>includeDeleted</code>' attribute. * * @param[in] value Whether to include changes indicating that items have * been removed from the list of changes, for example by deletion or loss of * access. */ void set_include_deleted(bool value) { _have_include_deleted_ = true; include_deleted_ = value; } /** * Clears the '<code>includeSubscribed</code>' attribute so it is no longer * set. */ void clear_include_subscribed() { _have_include_subscribed_ = false; client::ClearCppValueHelper(&include_subscribed_); } /** * Gets the optional '<code>includeSubscribed</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_include_subscribed() const { return include_subscribed_; } /** * Sets the '<code>includeSubscribed</code>' attribute. * * @param[in] value Whether to include public files the user has opened and * shared files. When set to false, the list only includes owned files plus * any shared or public files the user has explicitly added to a folder they * own. */ void set_include_subscribed(bool value) { _have_include_subscribed_ = true; include_subscribed_ = value; } /** * Clears the '<code>includeTeamDriveItems</code>' attribute so it is no * longer set. */ void clear_include_team_drive_items() { _have_include_team_drive_items_ = false; client::ClearCppValueHelper(&include_team_drive_items_); } /** * Gets the optional '<code>includeTeamDriveItems</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_include_team_drive_items() const { return include_team_drive_items_; } /** * Sets the '<code>includeTeamDriveItems</code>' attribute. * * @param[in] value Whether Team Drive files or changes should be included * in results. */ void set_include_team_drive_items(bool value) { _have_include_team_drive_items_ = true; include_team_drive_items_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ int32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value Maximum number of changes to return. */ void set_max_results(int32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The token for continuing a previous list request on the * next page. This should be set to the value of 'nextPageToken' from the * previous response or to the response from the getStartPageToken method. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Clears the '<code>spaces</code>' attribute so it is no longer set. */ void clear_spaces() { _have_spaces_ = false; client::ClearCppValueHelper(&spaces_); } /** * Gets the optional '<code>spaces</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_spaces() const { return spaces_; } /** * Gets a modifiable pointer to the optional <code>spaces</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_spaces() { _have_spaces_ = true; return &spaces_; } /** * Sets the '<code>spaces</code>' attribute. * * @param[in] value A comma-separated list of spaces to query. Supported * values are 'drive', 'appDataFolder' and 'photos'. */ void set_spaces(const string& value) { _have_spaces_ = true; spaces_ = value; } /** * Clears the '<code>startChangeId</code>' attribute so it is no longer set. */ void clear_start_change_id() { _have_start_change_id_ = false; client::ClearCppValueHelper(&start_change_id_); } /** * Gets the optional '<code>startChangeId</code>' attribute. * * If the value is not set then the default value will be returned. */ int64 get_start_change_id() const { return start_change_id_; } /** * Sets the '<code>startChangeId</code>' attribute. * * @param[in] value Change ID to start listing changes from. */ void set_start_change_id(int64 value) { _have_start_change_id_ = true; start_change_id_ = value; } /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Clears the '<code>teamDriveId</code>' attribute so it is no longer set. */ void clear_team_drive_id() { _have_team_drive_id_ = false; client::ClearCppValueHelper(&team_drive_id_); } /** * Gets the optional '<code>teamDriveId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_team_drive_id() const { return team_drive_id_; } /** * Gets a modifiable pointer to the optional <code>teamDriveId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_teamDriveId() { _have_team_drive_id_ = true; return &team_drive_id_; } /** * Sets the '<code>teamDriveId</code>' attribute. * * @param[in] value The Team Drive from which changes will be returned. If * specified the change IDs will be reflective of the Team Drive; use the * combined Team Drive ID and change ID as an identifier. */ void set_team_drive_id(const string& value) { _have_team_drive_id_ = true; team_drive_id_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( ChangeList* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: bool include_corpus_removals_; bool include_deleted_; bool include_subscribed_; bool include_team_drive_items_; int32 max_results_; string page_token_; string spaces_; int64 start_change_id_; bool supports_team_drives_; string team_drive_id_; bool _have_include_corpus_removals_ : 1; bool _have_include_deleted_ : 1; bool _have_include_subscribed_ : 1; bool _have_include_team_drive_items_ : 1; bool _have_max_results_ : 1; bool _have_page_token_ : 1; bool _have_spaces_ : 1; bool _have_start_change_id_ : 1; bool _have_supports_team_drives_ : 1; bool _have_team_drive_id_ : 1; DISALLOW_COPY_AND_ASSIGN(ChangesResource_ListMethod); }; typedef client::ServiceRequestPager< ChangesResource_ListMethod, ChangeList> ChangesResource_ListMethodPager; /** * Implements the watch method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.apps.readonly * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class ChangesResource_WatchMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] _content_ The data object to watch. */ ChangesResource_WatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const Channel& _content_); /** * Standard destructor. */ virtual ~ChangesResource_WatchMethod(); /** * Clears the '<code>includeCorpusRemovals</code>' attribute so it is no * longer set. */ void clear_include_corpus_removals() { _have_include_corpus_removals_ = false; client::ClearCppValueHelper(&include_corpus_removals_); } /** * Gets the optional '<code>includeCorpusRemovals</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_include_corpus_removals() const { return include_corpus_removals_; } /** * Sets the '<code>includeCorpusRemovals</code>' attribute. * * @param[in] value Whether changes should include the file resource if the * file is still accessible by the user at the time of the request, even * when a file was removed from the list of changes and there will be no * further change entries for this file. */ void set_include_corpus_removals(bool value) { _have_include_corpus_removals_ = true; include_corpus_removals_ = value; } /** * Clears the '<code>includeDeleted</code>' attribute so it is no longer * set. */ void clear_include_deleted() { _have_include_deleted_ = false; client::ClearCppValueHelper(&include_deleted_); } /** * Gets the optional '<code>includeDeleted</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_include_deleted() const { return include_deleted_; } /** * Sets the '<code>includeDeleted</code>' attribute. * * @param[in] value Whether to include changes indicating that items have * been removed from the list of changes, for example by deletion or loss of * access. */ void set_include_deleted(bool value) { _have_include_deleted_ = true; include_deleted_ = value; } /** * Clears the '<code>includeSubscribed</code>' attribute so it is no longer * set. */ void clear_include_subscribed() { _have_include_subscribed_ = false; client::ClearCppValueHelper(&include_subscribed_); } /** * Gets the optional '<code>includeSubscribed</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_include_subscribed() const { return include_subscribed_; } /** * Sets the '<code>includeSubscribed</code>' attribute. * * @param[in] value Whether to include public files the user has opened and * shared files. When set to false, the list only includes owned files plus * any shared or public files the user has explicitly added to a folder they * own. */ void set_include_subscribed(bool value) { _have_include_subscribed_ = true; include_subscribed_ = value; } /** * Clears the '<code>includeTeamDriveItems</code>' attribute so it is no * longer set. */ void clear_include_team_drive_items() { _have_include_team_drive_items_ = false; client::ClearCppValueHelper(&include_team_drive_items_); } /** * Gets the optional '<code>includeTeamDriveItems</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_include_team_drive_items() const { return include_team_drive_items_; } /** * Sets the '<code>includeTeamDriveItems</code>' attribute. * * @param[in] value Whether Team Drive files or changes should be included * in results. */ void set_include_team_drive_items(bool value) { _have_include_team_drive_items_ = true; include_team_drive_items_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ int32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value Maximum number of changes to return. */ void set_max_results(int32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The token for continuing a previous list request on the * next page. This should be set to the value of 'nextPageToken' from the * previous response or to the response from the getStartPageToken method. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Clears the '<code>spaces</code>' attribute so it is no longer set. */ void clear_spaces() { _have_spaces_ = false; client::ClearCppValueHelper(&spaces_); } /** * Gets the optional '<code>spaces</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_spaces() const { return spaces_; } /** * Gets a modifiable pointer to the optional <code>spaces</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_spaces() { _have_spaces_ = true; return &spaces_; } /** * Sets the '<code>spaces</code>' attribute. * * @param[in] value A comma-separated list of spaces to query. Supported * values are 'drive', 'appDataFolder' and 'photos'. */ void set_spaces(const string& value) { _have_spaces_ = true; spaces_ = value; } /** * Clears the '<code>startChangeId</code>' attribute so it is no longer set. */ void clear_start_change_id() { _have_start_change_id_ = false; client::ClearCppValueHelper(&start_change_id_); } /** * Gets the optional '<code>startChangeId</code>' attribute. * * If the value is not set then the default value will be returned. */ int64 get_start_change_id() const { return start_change_id_; } /** * Sets the '<code>startChangeId</code>' attribute. * * @param[in] value Change ID to start listing changes from. */ void set_start_change_id(int64 value) { _have_start_change_id_ = true; start_change_id_ = value; } /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Clears the '<code>teamDriveId</code>' attribute so it is no longer set. */ void clear_team_drive_id() { _have_team_drive_id_ = false; client::ClearCppValueHelper(&team_drive_id_); } /** * Gets the optional '<code>teamDriveId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_team_drive_id() const { return team_drive_id_; } /** * Gets a modifiable pointer to the optional <code>teamDriveId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_teamDriveId() { _have_team_drive_id_ = true; return &team_drive_id_; } /** * Sets the '<code>teamDriveId</code>' attribute. * * @param[in] value The Team Drive from which changes will be returned. If * specified the change IDs will be reflective of the Team Drive; use the * combined Team Drive ID and change ID as an identifier. */ void set_team_drive_id(const string& value) { _have_team_drive_id_ = true; team_drive_id_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Channel* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: bool include_corpus_removals_; bool include_deleted_; bool include_subscribed_; bool include_team_drive_items_; int32 max_results_; string page_token_; string spaces_; int64 start_change_id_; bool supports_team_drives_; string team_drive_id_; bool _have_include_corpus_removals_ : 1; bool _have_include_deleted_ : 1; bool _have_include_subscribed_ : 1; bool _have_include_team_drive_items_ : 1; bool _have_max_results_ : 1; bool _have_page_token_ : 1; bool _have_spaces_ : 1; bool _have_start_change_id_ : 1; bool _have_supports_team_drives_ : 1; bool _have_team_drive_id_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(ChangesResource_WatchMethod); }; /** * Implements the stop method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.apps.readonly * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class ChannelsResource_StopMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] _content_ The data object to stop. */ ChannelsResource_StopMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const Channel& _content_); /** * Standard destructor. */ virtual ~ChannelsResource_StopMethod(); private: string _content_; DISALLOW_COPY_AND_ASSIGN(ChannelsResource_StopMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file */ class ChildrenResource_DeleteMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] folder_id The ID of the folder. * @param[in] child_id The ID of the child. */ ChildrenResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& folder_id, const StringPiece& child_id); /** * Standard destructor. */ virtual ~ChildrenResource_DeleteMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); private: string folder_id_; string child_id_; DISALLOW_COPY_AND_ASSIGN(ChildrenResource_DeleteMethod); }; /** * Implements the get method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class ChildrenResource_GetMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] folder_id The ID of the folder. * @param[in] child_id The ID of the child. */ ChildrenResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& folder_id, const StringPiece& child_id); /** * Standard destructor. */ virtual ~ChildrenResource_GetMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( ChildReference* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string folder_id_; string child_id_; DISALLOW_COPY_AND_ASSIGN(ChildrenResource_GetMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file */ class ChildrenResource_InsertMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] folder_id The ID of the folder. * @param[in] _content_ The data object to insert. */ ChildrenResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& folder_id, const ChildReference& _content_); /** * Standard destructor. */ virtual ~ChildrenResource_InsertMethod(); /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( ChildReference* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string folder_id_; bool supports_team_drives_; bool _have_supports_team_drives_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(ChildrenResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class ChildrenResource_ListMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] folder_id The ID of the folder. */ ChildrenResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& folder_id); /** * Standard destructor. */ virtual ~ChildrenResource_ListMethod(); /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ int32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value Maximum number of children to return. */ void set_max_results(int32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>orderBy</code>' attribute so it is no longer set. */ void clear_order_by() { _have_order_by_ = false; client::ClearCppValueHelper(&order_by_); } /** * Gets the optional '<code>orderBy</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_order_by() const { return order_by_; } /** * Gets a modifiable pointer to the optional <code>orderBy</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_orderBy() { _have_order_by_ = true; return &order_by_; } /** * Sets the '<code>orderBy</code>' attribute. * * @param[in] value A comma-separated list of sort keys. Valid keys are * 'createdDate', 'folder', 'lastViewedByMeDate', 'modifiedByMeDate', * 'modifiedDate', 'quotaBytesUsed', 'recency', 'sharedWithMeDate', * 'starred', and 'title'. Each key sorts ascending by default, but may be * reversed with the 'desc' modifier. Example usage: * ?orderBy=folder,modifiedDate desc,title. Please note that there is a * current limitation for users with approximately one million files in * which the requested sort order is ignored. */ void set_order_by(const string& value) { _have_order_by_ = true; order_by_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value Page token for children. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Clears the '<code>q</code>' attribute so it is no longer set. */ void clear_q() { _have_q_ = false; client::ClearCppValueHelper(&q_); } /** * Gets the optional '<code>q</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_q() const { return q_; } /** * Gets a modifiable pointer to the optional <code>q</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_q() { _have_q_ = true; return &q_; } /** * Sets the '<code>q</code>' attribute. * * @param[in] value Query string for searching children. */ void set_q(const string& value) { _have_q_ = true; q_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( ChildList* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string folder_id_; int32 max_results_; string order_by_; string page_token_; string q_; bool _have_max_results_ : 1; bool _have_order_by_ : 1; bool _have_page_token_ : 1; bool _have_q_ : 1; DISALLOW_COPY_AND_ASSIGN(ChildrenResource_ListMethod); }; typedef client::ServiceRequestPager< ChildrenResource_ListMethod, ChildList> ChildrenResource_ListMethodPager; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file */ class CommentsResource_DeleteMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. */ CommentsResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id); /** * Standard destructor. */ virtual ~CommentsResource_DeleteMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); private: string file_id_; string comment_id_; DISALLOW_COPY_AND_ASSIGN(CommentsResource_DeleteMethod); }; /** * Implements the get method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.readonly */ class CommentsResource_GetMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. */ CommentsResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id); /** * Standard destructor. */ virtual ~CommentsResource_GetMethod(); /** * Clears the '<code>includeDeleted</code>' attribute so it is no longer * set. */ void clear_include_deleted() { _have_include_deleted_ = false; client::ClearCppValueHelper(&include_deleted_); } /** * Gets the optional '<code>includeDeleted</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_include_deleted() const { return include_deleted_; } /** * Sets the '<code>includeDeleted</code>' attribute. * * @param[in] value If set, this will succeed when retrieving a deleted * comment, and will include any deleted replies. */ void set_include_deleted(bool value) { _have_include_deleted_ = true; include_deleted_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Comment* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string comment_id_; bool include_deleted_; bool _have_include_deleted_ : 1; DISALLOW_COPY_AND_ASSIGN(CommentsResource_GetMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file */ class CommentsResource_InsertMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] _content_ The data object to insert. */ CommentsResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Comment& _content_); /** * Standard destructor. */ virtual ~CommentsResource_InsertMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Comment* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string _content_; DISALLOW_COPY_AND_ASSIGN(CommentsResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.readonly */ class CommentsResource_ListMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. */ CommentsResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id); /** * Standard destructor. */ virtual ~CommentsResource_ListMethod(); /** * Clears the '<code>includeDeleted</code>' attribute so it is no longer * set. */ void clear_include_deleted() { _have_include_deleted_ = false; client::ClearCppValueHelper(&include_deleted_); } /** * Gets the optional '<code>includeDeleted</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_include_deleted() const { return include_deleted_; } /** * Sets the '<code>includeDeleted</code>' attribute. * * @param[in] value If set, all comments and replies, including deleted * comments and replies (with content stripped) will be returned. */ void set_include_deleted(bool value) { _have_include_deleted_ = true; include_deleted_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ int32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maximum number of discussions to include in the * response, used for paging. */ void set_max_results(int32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The continuation token, used to page through large * result sets. To get the next page of results, set this parameter to the * value of "nextPageToken" from the previous response. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Clears the '<code>updatedMin</code>' attribute so it is no longer set. */ void clear_updated_min() { _have_updated_min_ = false; client::ClearCppValueHelper(&updated_min_); } /** * Gets the optional '<code>updatedMin</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_updated_min() const { return updated_min_; } /** * Gets a modifiable pointer to the optional <code>updatedMin</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_updatedMin() { _have_updated_min_ = true; return &updated_min_; } /** * Sets the '<code>updatedMin</code>' attribute. * * @param[in] value Only discussions that were updated after this timestamp * will be returned. Formatted as an RFC 3339 timestamp. */ void set_updated_min(const string& value) { _have_updated_min_ = true; updated_min_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( CommentList* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; bool include_deleted_; int32 max_results_; string page_token_; string updated_min_; bool _have_include_deleted_ : 1; bool _have_max_results_ : 1; bool _have_page_token_ : 1; bool _have_updated_min_ : 1; DISALLOW_COPY_AND_ASSIGN(CommentsResource_ListMethod); }; typedef client::ServiceRequestPager< CommentsResource_ListMethod, CommentList> CommentsResource_ListMethodPager; /** * Implements the patch method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file */ class CommentsResource_PatchMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @param[in] _content_ The data object to patch. */ CommentsResource_PatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const Comment& _content_); /** * Standard destructor. */ virtual ~CommentsResource_PatchMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Comment* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string comment_id_; string _content_; DISALLOW_COPY_AND_ASSIGN(CommentsResource_PatchMethod); }; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file */ class CommentsResource_UpdateMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @param[in] _content_ The data object to update. */ CommentsResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const Comment& _content_); /** * Standard destructor. */ virtual ~CommentsResource_UpdateMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Comment* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string comment_id_; string _content_; DISALLOW_COPY_AND_ASSIGN(CommentsResource_UpdateMethod); }; /** * Implements the copy method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.apps.readonly * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.photos.readonly */ class FilesResource_CopyMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file to copy. * @param[in] _content_ The data object to copy. */ FilesResource_CopyMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const File& _content_); /** * Standard destructor. */ virtual ~FilesResource_CopyMethod(); /** * Clears the '<code>convert</code>' attribute so it is no longer set. */ void clear_convert() { _have_convert_ = false; client::ClearCppValueHelper(&convert_); } /** * Gets the optional '<code>convert</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_convert() const { return convert_; } /** * Sets the '<code>convert</code>' attribute. * * @param[in] value Whether to convert this file to the corresponding Google * Docs format. */ void set_convert(bool value) { _have_convert_ = true; convert_ = value; } /** * Clears the '<code>ocr</code>' attribute so it is no longer set. */ void clear_ocr() { _have_ocr_ = false; client::ClearCppValueHelper(&ocr_); } /** * Gets the optional '<code>ocr</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_ocr() const { return ocr_; } /** * Sets the '<code>ocr</code>' attribute. * * @param[in] value Whether to attempt OCR on .jpg, .png, .gif, or .pdf * uploads. */ void set_ocr(bool value) { _have_ocr_ = true; ocr_ = value; } /** * Clears the '<code>ocrLanguage</code>' attribute so it is no longer set. */ void clear_ocr_language() { _have_ocr_language_ = false; client::ClearCppValueHelper(&ocr_language_); } /** * Gets the optional '<code>ocrLanguage</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_ocr_language() const { return ocr_language_; } /** * Gets a modifiable pointer to the optional <code>ocrLanguage</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_ocrLanguage() { _have_ocr_language_ = true; return &ocr_language_; } /** * Sets the '<code>ocrLanguage</code>' attribute. * * @param[in] value If ocr is true, hints at the language to use. Valid * values are BCP 47 codes. */ void set_ocr_language(const string& value) { _have_ocr_language_ = true; ocr_language_ = value; } /** * Clears the '<code>pinned</code>' attribute so it is no longer set. */ void clear_pinned() { _have_pinned_ = false; client::ClearCppValueHelper(&pinned_); } /** * Gets the optional '<code>pinned</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_pinned() const { return pinned_; } /** * Sets the '<code>pinned</code>' attribute. * * @param[in] value Whether to pin the head revision of the new copy. A file * can have a maximum of 200 pinned revisions. */ void set_pinned(bool value) { _have_pinned_ = true; pinned_ = value; } /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Clears the '<code>timedTextLanguage</code>' attribute so it is no longer * set. */ void clear_timed_text_language() { _have_timed_text_language_ = false; client::ClearCppValueHelper(&timed_text_language_); } /** * Gets the optional '<code>timedTextLanguage</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_timed_text_language() const { return timed_text_language_; } /** * Gets a modifiable pointer to the optional <code>timedTextLanguage</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_timedTextLanguage() { _have_timed_text_language_ = true; return &timed_text_language_; } /** * Sets the '<code>timedTextLanguage</code>' attribute. * * @param[in] value The language of the timed text. */ void set_timed_text_language(const string& value) { _have_timed_text_language_ = true; timed_text_language_ = value; } /** * Clears the '<code>timedTextTrackName</code>' attribute so it is no longer * set. */ void clear_timed_text_track_name() { _have_timed_text_track_name_ = false; client::ClearCppValueHelper(&timed_text_track_name_); } /** * Gets the optional '<code>timedTextTrackName</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_timed_text_track_name() const { return timed_text_track_name_; } /** * Gets a modifiable pointer to the optional * <code>timedTextTrackName</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_timedTextTrackName() { _have_timed_text_track_name_ = true; return &timed_text_track_name_; } /** * Sets the '<code>timedTextTrackName</code>' attribute. * * @param[in] value The timed text track name. */ void set_timed_text_track_name(const string& value) { _have_timed_text_track_name_ = true; timed_text_track_name_ = value; } /** * Clears the '<code>visibility</code>' attribute so it is no longer set. */ void clear_visibility() { _have_visibility_ = false; client::ClearCppValueHelper(&visibility_); } /** * Gets the optional '<code>visibility</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_visibility() const { return visibility_; } /** * Gets a modifiable pointer to the optional <code>visibility</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_visibility() { _have_visibility_ = true; return &visibility_; } /** * Sets the '<code>visibility</code>' attribute. * * @param[in] value The visibility of the new file. This parameter is only * relevant when the source is not a native Google Doc and convert=false. */ void set_visibility(const string& value) { _have_visibility_ = true; visibility_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( File* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; bool convert_; bool ocr_; string ocr_language_; bool pinned_; bool supports_team_drives_; string timed_text_language_; string timed_text_track_name_; string visibility_; bool _have_convert_ : 1; bool _have_ocr_ : 1; bool _have_ocr_language_ : 1; bool _have_pinned_ : 1; bool _have_supports_team_drives_ : 1; bool _have_timed_text_language_ : 1; bool _have_timed_text_track_name_ : 1; bool _have_visibility_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(FilesResource_CopyMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file */ class FilesResource_DeleteMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file to delete. */ FilesResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id); /** * Standard destructor. */ virtual ~FilesResource_DeleteMethod(); /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string file_id_; bool supports_team_drives_; bool _have_supports_team_drives_ : 1; DISALLOW_COPY_AND_ASSIGN(FilesResource_DeleteMethod); }; /** * Implements the emptyTrash method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive */ class FilesResource_EmptyTrashMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. */ FilesResource_EmptyTrashMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_); /** * Standard destructor. */ virtual ~FilesResource_EmptyTrashMethod(); private: DISALLOW_COPY_AND_ASSIGN(FilesResource_EmptyTrashMethod); }; /** * Implements the export method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.readonly */ class FilesResource_ExportMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] mime_type The MIME type of the format requested for this export. */ FilesResource_ExportMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& mime_type); /** * Standard destructor. */ virtual ~FilesResource_ExportMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Determine if the request should use Media Download for the response. * * @return true for media download, false otherwise. */ bool get_use_media_download() const { return DriveServiceBaseRequest::get_use_media_download(); } /** * Sets whether Media Download should be used for the response data. * * @param[in] use true to use media download, false otherwise. */ void set_use_media_download(bool use) { DriveServiceBaseRequest::set_use_media_download(use); } private: string file_id_; string mime_type_; DISALLOW_COPY_AND_ASSIGN(FilesResource_ExportMethod); }; /** * Implements the generateIds method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file */ class FilesResource_GenerateIdsMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. */ FilesResource_GenerateIdsMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_); /** * Standard destructor. */ virtual ~FilesResource_GenerateIdsMethod(); /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ int32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value Maximum number of IDs to return. */ void set_max_results(int32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>space</code>' attribute so it is no longer set. */ void clear_space() { _have_space_ = false; client::ClearCppValueHelper(&space_); } /** * Gets the optional '<code>space</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_space() const { return space_; } /** * Gets a modifiable pointer to the optional <code>space</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_space() { _have_space_ = true; return &space_; } /** * Sets the '<code>space</code>' attribute. * * @param[in] value The space in which the IDs can be used to create new * files. Supported values are 'drive' and 'appDataFolder'. */ void set_space(const string& value) { _have_space_ = true; space_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( GeneratedIds* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: int32 max_results_; string space_; bool _have_max_results_ : 1; bool _have_space_ : 1; DISALLOW_COPY_AND_ASSIGN(FilesResource_GenerateIdsMethod); }; /** * Implements the get method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class FilesResource_GetMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID for the file in question. */ FilesResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id); /** * Standard destructor. */ virtual ~FilesResource_GetMethod(); /** * Clears the '<code>acknowledgeAbuse</code>' attribute so it is no longer * set. */ void clear_acknowledge_abuse() { _have_acknowledge_abuse_ = false; client::ClearCppValueHelper(&acknowledge_abuse_); } /** * Gets the optional '<code>acknowledgeAbuse</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_acknowledge_abuse() const { return acknowledge_abuse_; } /** * Sets the '<code>acknowledgeAbuse</code>' attribute. * * @param[in] value Whether the user is acknowledging the risk of * downloading known malware or other abusive files. */ void set_acknowledge_abuse(bool value) { _have_acknowledge_abuse_ = true; acknowledge_abuse_ = value; } /** * Clears the '<code>projection</code>' attribute so it is no longer set. */ void clear_projection() { _have_projection_ = false; client::ClearCppValueHelper(&projection_); } /** * Gets the optional '<code>projection</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_projection() const { return projection_; } /** * Gets a modifiable pointer to the optional <code>projection</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_projection() { _have_projection_ = true; return &projection_; } /** * Sets the '<code>projection</code>' attribute. * * @param[in] value This parameter is deprecated and has no function. */ void set_projection(const string& value) { _have_projection_ = true; projection_ = value; } /** * Clears the '<code>revisionId</code>' attribute so it is no longer set. */ void clear_revision_id() { _have_revision_id_ = false; client::ClearCppValueHelper(&revision_id_); } /** * Gets the optional '<code>revisionId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_revision_id() const { return revision_id_; } /** * Gets a modifiable pointer to the optional <code>revisionId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_revisionId() { _have_revision_id_ = true; return &revision_id_; } /** * Sets the '<code>revisionId</code>' attribute. * * @param[in] value Specifies the Revision ID that should be downloaded. * Ignored unless alt=media is specified. */ void set_revision_id(const string& value) { _have_revision_id_ = true; revision_id_ = value; } /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Clears the '<code>updateViewedDate</code>' attribute so it is no longer * set. */ void clear_update_viewed_date() { _have_update_viewed_date_ = false; client::ClearCppValueHelper(&update_viewed_date_); } /** * Gets the optional '<code>updateViewedDate</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_update_viewed_date() const { return update_viewed_date_; } /** * Sets the '<code>updateViewedDate</code>' attribute. * @deprecated * * @param[in] value Deprecated: Use files.update with * modifiedDateBehavior=noChange, updateViewedDate=true and an empty request * body. */ void set_update_viewed_date(bool value) { _have_update_viewed_date_ = true; update_viewed_date_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( File* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } /** * Determine if the request should use Media Download for the response. * * @return true for media download, false otherwise. */ bool get_use_media_download() const { return DriveServiceBaseRequest::get_use_media_download(); } /** * Sets whether Media Download should be used for the response data. * * @param[in] use true to use media download, false otherwise. */ void set_use_media_download(bool use) { DriveServiceBaseRequest::set_use_media_download(use); } private: string file_id_; bool acknowledge_abuse_; string projection_; string revision_id_; bool supports_team_drives_; bool update_viewed_date_; bool _have_acknowledge_abuse_ : 1; bool _have_projection_ : 1; bool _have_revision_id_ : 1; bool _have_supports_team_drives_ : 1; bool _have_update_viewed_date_ : 1; DISALLOW_COPY_AND_ASSIGN(FilesResource_GetMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.apps.readonly * https://www.googleapis.com/auth/drive.file */ class FilesResource_InsertMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * * @deprecated in favor constructor that includes the media upload parameters. * * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] _content_ The data object to insert. */ FilesResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_); /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] _metadata_ The metadata object to insert. If this * is NULL then do not upload any metadata. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to insert. If * this is NULL then do not upload any media and ignore * _media_content_type_. */ FilesResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const File* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_); /** * Standard destructor. */ virtual ~FilesResource_InsertMethod(); /** * Clears the '<code>convert</code>' attribute so it is no longer set. */ void clear_convert() { _have_convert_ = false; client::ClearCppValueHelper(&convert_); } /** * Gets the optional '<code>convert</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_convert() const { return convert_; } /** * Sets the '<code>convert</code>' attribute. * * @param[in] value Whether to convert this file to the corresponding Google * Docs format. */ void set_convert(bool value) { _have_convert_ = true; convert_ = value; } /** * Clears the '<code>ocr</code>' attribute so it is no longer set. */ void clear_ocr() { _have_ocr_ = false; client::ClearCppValueHelper(&ocr_); } /** * Gets the optional '<code>ocr</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_ocr() const { return ocr_; } /** * Sets the '<code>ocr</code>' attribute. * * @param[in] value Whether to attempt OCR on .jpg, .png, .gif, or .pdf * uploads. */ void set_ocr(bool value) { _have_ocr_ = true; ocr_ = value; } /** * Clears the '<code>ocrLanguage</code>' attribute so it is no longer set. */ void clear_ocr_language() { _have_ocr_language_ = false; client::ClearCppValueHelper(&ocr_language_); } /** * Gets the optional '<code>ocrLanguage</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_ocr_language() const { return ocr_language_; } /** * Gets a modifiable pointer to the optional <code>ocrLanguage</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_ocrLanguage() { _have_ocr_language_ = true; return &ocr_language_; } /** * Sets the '<code>ocrLanguage</code>' attribute. * * @param[in] value If ocr is true, hints at the language to use. Valid * values are BCP 47 codes. */ void set_ocr_language(const string& value) { _have_ocr_language_ = true; ocr_language_ = value; } /** * Clears the '<code>pinned</code>' attribute so it is no longer set. */ void clear_pinned() { _have_pinned_ = false; client::ClearCppValueHelper(&pinned_); } /** * Gets the optional '<code>pinned</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_pinned() const { return pinned_; } /** * Sets the '<code>pinned</code>' attribute. * * @param[in] value Whether to pin the head revision of the uploaded file. A * file can have a maximum of 200 pinned revisions. */ void set_pinned(bool value) { _have_pinned_ = true; pinned_ = value; } /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Clears the '<code>timedTextLanguage</code>' attribute so it is no longer * set. */ void clear_timed_text_language() { _have_timed_text_language_ = false; client::ClearCppValueHelper(&timed_text_language_); } /** * Gets the optional '<code>timedTextLanguage</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_timed_text_language() const { return timed_text_language_; } /** * Gets a modifiable pointer to the optional <code>timedTextLanguage</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_timedTextLanguage() { _have_timed_text_language_ = true; return &timed_text_language_; } /** * Sets the '<code>timedTextLanguage</code>' attribute. * * @param[in] value The language of the timed text. */ void set_timed_text_language(const string& value) { _have_timed_text_language_ = true; timed_text_language_ = value; } /** * Clears the '<code>timedTextTrackName</code>' attribute so it is no longer * set. */ void clear_timed_text_track_name() { _have_timed_text_track_name_ = false; client::ClearCppValueHelper(&timed_text_track_name_); } /** * Gets the optional '<code>timedTextTrackName</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_timed_text_track_name() const { return timed_text_track_name_; } /** * Gets a modifiable pointer to the optional * <code>timedTextTrackName</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_timedTextTrackName() { _have_timed_text_track_name_ = true; return &timed_text_track_name_; } /** * Sets the '<code>timedTextTrackName</code>' attribute. * * @param[in] value The timed text track name. */ void set_timed_text_track_name(const string& value) { _have_timed_text_track_name_ = true; timed_text_track_name_ = value; } /** * Clears the '<code>useContentAsIndexableText</code>' attribute so it is no * longer set. */ void clear_use_content_as_indexable_text() { _have_use_content_as_indexable_text_ = false; client::ClearCppValueHelper(&use_content_as_indexable_text_); } /** * Gets the optional '<code>useContentAsIndexableText</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_use_content_as_indexable_text() const { return use_content_as_indexable_text_; } /** * Sets the '<code>useContentAsIndexableText</code>' attribute. * * @param[in] value Whether to use the content as indexable text. */ void set_use_content_as_indexable_text(bool value) { _have_use_content_as_indexable_text_ = true; use_content_as_indexable_text_ = value; } /** * Clears the '<code>visibility</code>' attribute so it is no longer set. */ void clear_visibility() { _have_visibility_ = false; client::ClearCppValueHelper(&visibility_); } /** * Gets the optional '<code>visibility</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_visibility() const { return visibility_; } /** * Gets a modifiable pointer to the optional <code>visibility</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_visibility() { _have_visibility_ = true; return &visibility_; } /** * Sets the '<code>visibility</code>' attribute. * * @param[in] value The visibility of the new file. This parameter is only * relevant when convert=false. */ void set_visibility(const string& value) { _have_visibility_ = true; visibility_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( File* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } /** * Returns MediaUploader for uploading the content. */ /** * Returns the specification for media upload using the simple protocol. */ static const client::MediaUploadSpec SIMPLE_MEDIA_UPLOAD; /** * Returns the specification for media upload using the resumable protocol. */ static const client::MediaUploadSpec RESUMABLE_MEDIA_UPLOAD; private: bool convert_; bool ocr_; string ocr_language_; bool pinned_; bool supports_team_drives_; string timed_text_language_; string timed_text_track_name_; bool use_content_as_indexable_text_; string visibility_; bool _have_convert_ : 1; bool _have_ocr_ : 1; bool _have_ocr_language_ : 1; bool _have_pinned_ : 1; bool _have_supports_team_drives_ : 1; bool _have_timed_text_language_ : 1; bool _have_timed_text_track_name_ : 1; bool _have_use_content_as_indexable_text_ : 1; bool _have_visibility_ : 1; DISALLOW_COPY_AND_ASSIGN(FilesResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.apps.readonly * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class FilesResource_ListMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. */ FilesResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_); /** * Standard destructor. */ virtual ~FilesResource_ListMethod(); /** * Clears the '<code>corpora</code>' attribute so it is no longer set. */ void clear_corpora() { _have_corpora_ = false; client::ClearCppValueHelper(&corpora_); } /** * Gets the optional '<code>corpora</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_corpora() const { return corpora_; } /** * Gets a modifiable pointer to the optional <code>corpora</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_corpora() { _have_corpora_ = true; return &corpora_; } /** * Sets the '<code>corpora</code>' attribute. * * @param[in] value Comma-separated list of bodies of items * (files/documents) to which the query applies. Supported bodies are * 'default', 'domain', 'teamDrive' and 'allTeamDrives'. 'allTeamDrives' * must be combined with 'default'; all other values must be used in * isolation. Prefer 'default' or 'teamDrive' to 'allTeamDrives' for * efficiency. */ void set_corpora(const string& value) { _have_corpora_ = true; corpora_ = value; } /** * Clears the '<code>corpus</code>' attribute so it is no longer set. */ void clear_corpus() { _have_corpus_ = false; client::ClearCppValueHelper(&corpus_); } /** * Gets the optional '<code>corpus</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_corpus() const { return corpus_; } /** * Gets a modifiable pointer to the optional <code>corpus</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_corpus() { _have_corpus_ = true; return &corpus_; } /** * Sets the '<code>corpus</code>' attribute. * * @param[in] value The body of items (files/documents) to which the query * applies. Deprecated: use 'corpora' instead. */ void set_corpus(const string& value) { _have_corpus_ = true; corpus_ = value; } /** * Clears the '<code>includeTeamDriveItems</code>' attribute so it is no * longer set. */ void clear_include_team_drive_items() { _have_include_team_drive_items_ = false; client::ClearCppValueHelper(&include_team_drive_items_); } /** * Gets the optional '<code>includeTeamDriveItems</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_include_team_drive_items() const { return include_team_drive_items_; } /** * Sets the '<code>includeTeamDriveItems</code>' attribute. * * @param[in] value Whether Team Drive items should be included in results. */ void set_include_team_drive_items(bool value) { _have_include_team_drive_items_ = true; include_team_drive_items_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ int32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maximum number of files to return per page. Partial * or empty result pages are possible even before the end of the files list * has been reached. */ void set_max_results(int32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>orderBy</code>' attribute so it is no longer set. */ void clear_order_by() { _have_order_by_ = false; client::ClearCppValueHelper(&order_by_); } /** * Gets the optional '<code>orderBy</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_order_by() const { return order_by_; } /** * Gets a modifiable pointer to the optional <code>orderBy</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_orderBy() { _have_order_by_ = true; return &order_by_; } /** * Sets the '<code>orderBy</code>' attribute. * * @param[in] value A comma-separated list of sort keys. Valid keys are * 'createdDate', 'folder', 'lastViewedByMeDate', 'modifiedByMeDate', * 'modifiedDate', 'quotaBytesUsed', 'recency', 'sharedWithMeDate', * 'starred', and 'title'. Each key sorts ascending by default, but may be * reversed with the 'desc' modifier. Example usage: * ?orderBy=folder,modifiedDate desc,title. Please note that there is a * current limitation for users with approximately one million files in * which the requested sort order is ignored. */ void set_order_by(const string& value) { _have_order_by_ = true; order_by_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value Page token for files. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Clears the '<code>projection</code>' attribute so it is no longer set. */ void clear_projection() { _have_projection_ = false; client::ClearCppValueHelper(&projection_); } /** * Gets the optional '<code>projection</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_projection() const { return projection_; } /** * Gets a modifiable pointer to the optional <code>projection</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_projection() { _have_projection_ = true; return &projection_; } /** * Sets the '<code>projection</code>' attribute. * * @param[in] value This parameter is deprecated and has no function. */ void set_projection(const string& value) { _have_projection_ = true; projection_ = value; } /** * Clears the '<code>q</code>' attribute so it is no longer set. */ void clear_q() { _have_q_ = false; client::ClearCppValueHelper(&q_); } /** * Gets the optional '<code>q</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_q() const { return q_; } /** * Gets a modifiable pointer to the optional <code>q</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_q() { _have_q_ = true; return &q_; } /** * Sets the '<code>q</code>' attribute. * * @param[in] value Query string for searching files. */ void set_q(const string& value) { _have_q_ = true; q_ = value; } /** * Clears the '<code>spaces</code>' attribute so it is no longer set. */ void clear_spaces() { _have_spaces_ = false; client::ClearCppValueHelper(&spaces_); } /** * Gets the optional '<code>spaces</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_spaces() const { return spaces_; } /** * Gets a modifiable pointer to the optional <code>spaces</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_spaces() { _have_spaces_ = true; return &spaces_; } /** * Sets the '<code>spaces</code>' attribute. * * @param[in] value A comma-separated list of spaces to query. Supported * values are 'drive', 'appDataFolder' and 'photos'. */ void set_spaces(const string& value) { _have_spaces_ = true; spaces_ = value; } /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Clears the '<code>teamDriveId</code>' attribute so it is no longer set. */ void clear_team_drive_id() { _have_team_drive_id_ = false; client::ClearCppValueHelper(&team_drive_id_); } /** * Gets the optional '<code>teamDriveId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_team_drive_id() const { return team_drive_id_; } /** * Gets a modifiable pointer to the optional <code>teamDriveId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_teamDriveId() { _have_team_drive_id_ = true; return &team_drive_id_; } /** * Sets the '<code>teamDriveId</code>' attribute. * * @param[in] value ID of Team Drive to search. */ void set_team_drive_id(const string& value) { _have_team_drive_id_ = true; team_drive_id_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( FileList* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string corpora_; string corpus_; bool include_team_drive_items_; int32 max_results_; string order_by_; string page_token_; string projection_; string q_; string spaces_; bool supports_team_drives_; string team_drive_id_; bool _have_corpora_ : 1; bool _have_corpus_ : 1; bool _have_include_team_drive_items_ : 1; bool _have_max_results_ : 1; bool _have_order_by_ : 1; bool _have_page_token_ : 1; bool _have_projection_ : 1; bool _have_q_ : 1; bool _have_spaces_ : 1; bool _have_supports_team_drives_ : 1; bool _have_team_drive_id_ : 1; DISALLOW_COPY_AND_ASSIGN(FilesResource_ListMethod); }; typedef client::ServiceRequestPager< FilesResource_ListMethod, FileList> FilesResource_ListMethodPager; /** * Implements the patch method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.apps.readonly * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.scripts */ class FilesResource_PatchMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file to update. * @param[in] _content_ The data object to patch. */ FilesResource_PatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const File& _content_); /** * Standard destructor. */ virtual ~FilesResource_PatchMethod(); /** * Clears the '<code>addParents</code>' attribute so it is no longer set. */ void clear_add_parents() { _have_add_parents_ = false; client::ClearCppValueHelper(&add_parents_); } /** * Gets the optional '<code>addParents</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_add_parents() const { return add_parents_; } /** * Gets a modifiable pointer to the optional <code>addParents</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_addParents() { _have_add_parents_ = true; return &add_parents_; } /** * Sets the '<code>addParents</code>' attribute. * * @param[in] value Comma-separated list of parent IDs to add. */ void set_add_parents(const string& value) { _have_add_parents_ = true; add_parents_ = value; } /** * Clears the '<code>convert</code>' attribute so it is no longer set. */ void clear_convert() { _have_convert_ = false; client::ClearCppValueHelper(&convert_); } /** * Gets the optional '<code>convert</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_convert() const { return convert_; } /** * Sets the '<code>convert</code>' attribute. * * @param[in] value This parameter is deprecated and has no function. */ void set_convert(bool value) { _have_convert_ = true; convert_ = value; } /** * Clears the '<code>modifiedDateBehavior</code>' attribute so it is no * longer set. */ void clear_modified_date_behavior() { _have_modified_date_behavior_ = false; client::ClearCppValueHelper(&modified_date_behavior_); } /** * Gets the optional '<code>modifiedDateBehavior</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_modified_date_behavior() const { return modified_date_behavior_; } /** * Gets a modifiable pointer to the optional * <code>modifiedDateBehavior</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_modifiedDateBehavior() { _have_modified_date_behavior_ = true; return &modified_date_behavior_; } /** * Sets the '<code>modifiedDateBehavior</code>' attribute. * * @param[in] value Determines the behavior in which modifiedDate is * updated. This overrides setModifiedDate. */ void set_modified_date_behavior(const string& value) { _have_modified_date_behavior_ = true; modified_date_behavior_ = value; } /** * Clears the '<code>newRevision</code>' attribute so it is no longer set. */ void clear_new_revision() { _have_new_revision_ = false; client::ClearCppValueHelper(&new_revision_); } /** * Gets the optional '<code>newRevision</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_new_revision() const { return new_revision_; } /** * Sets the '<code>newRevision</code>' attribute. * * @param[in] value Whether a blob upload should create a new revision. If * false, the blob data in the current head revision is replaced. If true or * not set, a new blob is created as head revision, and previous unpinned * revisions are preserved for a short period of time. Pinned revisions are * stored indefinitely, using additional storage quota, up to a maximum of * 200 revisions. For details on how revisions are retained, see the Drive * Help Center. */ void set_new_revision(bool value) { _have_new_revision_ = true; new_revision_ = value; } /** * Clears the '<code>ocr</code>' attribute so it is no longer set. */ void clear_ocr() { _have_ocr_ = false; client::ClearCppValueHelper(&ocr_); } /** * Gets the optional '<code>ocr</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_ocr() const { return ocr_; } /** * Sets the '<code>ocr</code>' attribute. * * @param[in] value Whether to attempt OCR on .jpg, .png, .gif, or .pdf * uploads. */ void set_ocr(bool value) { _have_ocr_ = true; ocr_ = value; } /** * Clears the '<code>ocrLanguage</code>' attribute so it is no longer set. */ void clear_ocr_language() { _have_ocr_language_ = false; client::ClearCppValueHelper(&ocr_language_); } /** * Gets the optional '<code>ocrLanguage</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_ocr_language() const { return ocr_language_; } /** * Gets a modifiable pointer to the optional <code>ocrLanguage</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_ocrLanguage() { _have_ocr_language_ = true; return &ocr_language_; } /** * Sets the '<code>ocrLanguage</code>' attribute. * * @param[in] value If ocr is true, hints at the language to use. Valid * values are BCP 47 codes. */ void set_ocr_language(const string& value) { _have_ocr_language_ = true; ocr_language_ = value; } /** * Clears the '<code>pinned</code>' attribute so it is no longer set. */ void clear_pinned() { _have_pinned_ = false; client::ClearCppValueHelper(&pinned_); } /** * Gets the optional '<code>pinned</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_pinned() const { return pinned_; } /** * Sets the '<code>pinned</code>' attribute. * * @param[in] value Whether to pin the new revision. A file can have a * maximum of 200 pinned revisions. */ void set_pinned(bool value) { _have_pinned_ = true; pinned_ = value; } /** * Clears the '<code>removeParents</code>' attribute so it is no longer set. */ void clear_remove_parents() { _have_remove_parents_ = false; client::ClearCppValueHelper(&remove_parents_); } /** * Gets the optional '<code>removeParents</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_remove_parents() const { return remove_parents_; } /** * Gets a modifiable pointer to the optional <code>removeParents</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_removeParents() { _have_remove_parents_ = true; return &remove_parents_; } /** * Sets the '<code>removeParents</code>' attribute. * * @param[in] value Comma-separated list of parent IDs to remove. */ void set_remove_parents(const string& value) { _have_remove_parents_ = true; remove_parents_ = value; } /** * Clears the '<code>setModifiedDate</code>' attribute so it is no longer * set. */ void clear_set_modified_date() { _have_set_modified_date_ = false; client::ClearCppValueHelper(&set_modified_date_); } /** * Gets the optional '<code>setModifiedDate</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_set_modified_date() const { return set_modified_date_; } /** * Sets the '<code>setModifiedDate</code>' attribute. * * @param[in] value Whether to set the modified date with the supplied * modified date. */ void set_set_modified_date(bool value) { _have_set_modified_date_ = true; set_modified_date_ = value; } /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Clears the '<code>timedTextLanguage</code>' attribute so it is no longer * set. */ void clear_timed_text_language() { _have_timed_text_language_ = false; client::ClearCppValueHelper(&timed_text_language_); } /** * Gets the optional '<code>timedTextLanguage</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_timed_text_language() const { return timed_text_language_; } /** * Gets a modifiable pointer to the optional <code>timedTextLanguage</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_timedTextLanguage() { _have_timed_text_language_ = true; return &timed_text_language_; } /** * Sets the '<code>timedTextLanguage</code>' attribute. * * @param[in] value The language of the timed text. */ void set_timed_text_language(const string& value) { _have_timed_text_language_ = true; timed_text_language_ = value; } /** * Clears the '<code>timedTextTrackName</code>' attribute so it is no longer * set. */ void clear_timed_text_track_name() { _have_timed_text_track_name_ = false; client::ClearCppValueHelper(&timed_text_track_name_); } /** * Gets the optional '<code>timedTextTrackName</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_timed_text_track_name() const { return timed_text_track_name_; } /** * Gets a modifiable pointer to the optional * <code>timedTextTrackName</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_timedTextTrackName() { _have_timed_text_track_name_ = true; return &timed_text_track_name_; } /** * Sets the '<code>timedTextTrackName</code>' attribute. * * @param[in] value The timed text track name. */ void set_timed_text_track_name(const string& value) { _have_timed_text_track_name_ = true; timed_text_track_name_ = value; } /** * Clears the '<code>updateViewedDate</code>' attribute so it is no longer * set. */ void clear_update_viewed_date() { _have_update_viewed_date_ = false; client::ClearCppValueHelper(&update_viewed_date_); } /** * Gets the optional '<code>updateViewedDate</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_update_viewed_date() const { return update_viewed_date_; } /** * Sets the '<code>updateViewedDate</code>' attribute. * * @param[in] value Whether to update the view date after successfully * updating the file. */ void set_update_viewed_date(bool value) { _have_update_viewed_date_ = true; update_viewed_date_ = value; } /** * Clears the '<code>useContentAsIndexableText</code>' attribute so it is no * longer set. */ void clear_use_content_as_indexable_text() { _have_use_content_as_indexable_text_ = false; client::ClearCppValueHelper(&use_content_as_indexable_text_); } /** * Gets the optional '<code>useContentAsIndexableText</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_use_content_as_indexable_text() const { return use_content_as_indexable_text_; } /** * Sets the '<code>useContentAsIndexableText</code>' attribute. * * @param[in] value Whether to use the content as indexable text. */ void set_use_content_as_indexable_text(bool value) { _have_use_content_as_indexable_text_ = true; use_content_as_indexable_text_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( File* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string add_parents_; bool convert_; string modified_date_behavior_; bool new_revision_; bool ocr_; string ocr_language_; bool pinned_; string remove_parents_; bool set_modified_date_; bool supports_team_drives_; string timed_text_language_; string timed_text_track_name_; bool update_viewed_date_; bool use_content_as_indexable_text_; bool _have_add_parents_ : 1; bool _have_convert_ : 1; bool _have_modified_date_behavior_ : 1; bool _have_new_revision_ : 1; bool _have_ocr_ : 1; bool _have_ocr_language_ : 1; bool _have_pinned_ : 1; bool _have_remove_parents_ : 1; bool _have_set_modified_date_ : 1; bool _have_supports_team_drives_ : 1; bool _have_timed_text_language_ : 1; bool _have_timed_text_track_name_ : 1; bool _have_update_viewed_date_ : 1; bool _have_use_content_as_indexable_text_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(FilesResource_PatchMethod); }; /** * Implements the touch method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.apps.readonly * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata */ class FilesResource_TouchMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file to update. */ FilesResource_TouchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id); /** * Standard destructor. */ virtual ~FilesResource_TouchMethod(); /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( File* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; bool supports_team_drives_; bool _have_supports_team_drives_ : 1; DISALLOW_COPY_AND_ASSIGN(FilesResource_TouchMethod); }; /** * Implements the trash method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.apps.readonly * https://www.googleapis.com/auth/drive.file */ class FilesResource_TrashMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file to trash. */ FilesResource_TrashMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id); /** * Standard destructor. */ virtual ~FilesResource_TrashMethod(); /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( File* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; bool supports_team_drives_; bool _have_supports_team_drives_ : 1; DISALLOW_COPY_AND_ASSIGN(FilesResource_TrashMethod); }; /** * Implements the untrash method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.apps.readonly * https://www.googleapis.com/auth/drive.file */ class FilesResource_UntrashMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file to untrash. */ FilesResource_UntrashMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id); /** * Standard destructor. */ virtual ~FilesResource_UntrashMethod(); /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( File* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; bool supports_team_drives_; bool _have_supports_team_drives_ : 1; DISALLOW_COPY_AND_ASSIGN(FilesResource_UntrashMethod); }; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.apps.readonly * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.scripts */ class FilesResource_UpdateMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * * @deprecated in favor constructor that includes the media upload parameters. * * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file to update. * * @param[in] _content_ The data object to update. */ FilesResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id); /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file to update. * @param[in] _metadata_ The metadata object to update. If this * is NULL then do not upload any metadata. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to update. If * this is NULL then do not upload any media and ignore * _media_content_type_. */ FilesResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const File* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_); /** * Standard destructor. */ virtual ~FilesResource_UpdateMethod(); /** * Clears the '<code>addParents</code>' attribute so it is no longer set. */ void clear_add_parents() { _have_add_parents_ = false; client::ClearCppValueHelper(&add_parents_); } /** * Gets the optional '<code>addParents</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_add_parents() const { return add_parents_; } /** * Gets a modifiable pointer to the optional <code>addParents</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_addParents() { _have_add_parents_ = true; return &add_parents_; } /** * Sets the '<code>addParents</code>' attribute. * * @param[in] value Comma-separated list of parent IDs to add. */ void set_add_parents(const string& value) { _have_add_parents_ = true; add_parents_ = value; } /** * Clears the '<code>convert</code>' attribute so it is no longer set. */ void clear_convert() { _have_convert_ = false; client::ClearCppValueHelper(&convert_); } /** * Gets the optional '<code>convert</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_convert() const { return convert_; } /** * Sets the '<code>convert</code>' attribute. * * @param[in] value This parameter is deprecated and has no function. */ void set_convert(bool value) { _have_convert_ = true; convert_ = value; } /** * Clears the '<code>modifiedDateBehavior</code>' attribute so it is no * longer set. */ void clear_modified_date_behavior() { _have_modified_date_behavior_ = false; client::ClearCppValueHelper(&modified_date_behavior_); } /** * Gets the optional '<code>modifiedDateBehavior</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_modified_date_behavior() const { return modified_date_behavior_; } /** * Gets a modifiable pointer to the optional * <code>modifiedDateBehavior</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_modifiedDateBehavior() { _have_modified_date_behavior_ = true; return &modified_date_behavior_; } /** * Sets the '<code>modifiedDateBehavior</code>' attribute. * * @param[in] value Determines the behavior in which modifiedDate is * updated. This overrides setModifiedDate. */ void set_modified_date_behavior(const string& value) { _have_modified_date_behavior_ = true; modified_date_behavior_ = value; } /** * Clears the '<code>newRevision</code>' attribute so it is no longer set. */ void clear_new_revision() { _have_new_revision_ = false; client::ClearCppValueHelper(&new_revision_); } /** * Gets the optional '<code>newRevision</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_new_revision() const { return new_revision_; } /** * Sets the '<code>newRevision</code>' attribute. * * @param[in] value Whether a blob upload should create a new revision. If * false, the blob data in the current head revision is replaced. If true or * not set, a new blob is created as head revision, and previous unpinned * revisions are preserved for a short period of time. Pinned revisions are * stored indefinitely, using additional storage quota, up to a maximum of * 200 revisions. For details on how revisions are retained, see the Drive * Help Center. */ void set_new_revision(bool value) { _have_new_revision_ = true; new_revision_ = value; } /** * Clears the '<code>ocr</code>' attribute so it is no longer set. */ void clear_ocr() { _have_ocr_ = false; client::ClearCppValueHelper(&ocr_); } /** * Gets the optional '<code>ocr</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_ocr() const { return ocr_; } /** * Sets the '<code>ocr</code>' attribute. * * @param[in] value Whether to attempt OCR on .jpg, .png, .gif, or .pdf * uploads. */ void set_ocr(bool value) { _have_ocr_ = true; ocr_ = value; } /** * Clears the '<code>ocrLanguage</code>' attribute so it is no longer set. */ void clear_ocr_language() { _have_ocr_language_ = false; client::ClearCppValueHelper(&ocr_language_); } /** * Gets the optional '<code>ocrLanguage</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_ocr_language() const { return ocr_language_; } /** * Gets a modifiable pointer to the optional <code>ocrLanguage</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_ocrLanguage() { _have_ocr_language_ = true; return &ocr_language_; } /** * Sets the '<code>ocrLanguage</code>' attribute. * * @param[in] value If ocr is true, hints at the language to use. Valid * values are BCP 47 codes. */ void set_ocr_language(const string& value) { _have_ocr_language_ = true; ocr_language_ = value; } /** * Clears the '<code>pinned</code>' attribute so it is no longer set. */ void clear_pinned() { _have_pinned_ = false; client::ClearCppValueHelper(&pinned_); } /** * Gets the optional '<code>pinned</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_pinned() const { return pinned_; } /** * Sets the '<code>pinned</code>' attribute. * * @param[in] value Whether to pin the new revision. A file can have a * maximum of 200 pinned revisions. */ void set_pinned(bool value) { _have_pinned_ = true; pinned_ = value; } /** * Clears the '<code>removeParents</code>' attribute so it is no longer set. */ void clear_remove_parents() { _have_remove_parents_ = false; client::ClearCppValueHelper(&remove_parents_); } /** * Gets the optional '<code>removeParents</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_remove_parents() const { return remove_parents_; } /** * Gets a modifiable pointer to the optional <code>removeParents</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_removeParents() { _have_remove_parents_ = true; return &remove_parents_; } /** * Sets the '<code>removeParents</code>' attribute. * * @param[in] value Comma-separated list of parent IDs to remove. */ void set_remove_parents(const string& value) { _have_remove_parents_ = true; remove_parents_ = value; } /** * Clears the '<code>setModifiedDate</code>' attribute so it is no longer * set. */ void clear_set_modified_date() { _have_set_modified_date_ = false; client::ClearCppValueHelper(&set_modified_date_); } /** * Gets the optional '<code>setModifiedDate</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_set_modified_date() const { return set_modified_date_; } /** * Sets the '<code>setModifiedDate</code>' attribute. * * @param[in] value Whether to set the modified date with the supplied * modified date. */ void set_set_modified_date(bool value) { _have_set_modified_date_ = true; set_modified_date_ = value; } /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Clears the '<code>timedTextLanguage</code>' attribute so it is no longer * set. */ void clear_timed_text_language() { _have_timed_text_language_ = false; client::ClearCppValueHelper(&timed_text_language_); } /** * Gets the optional '<code>timedTextLanguage</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_timed_text_language() const { return timed_text_language_; } /** * Gets a modifiable pointer to the optional <code>timedTextLanguage</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_timedTextLanguage() { _have_timed_text_language_ = true; return &timed_text_language_; } /** * Sets the '<code>timedTextLanguage</code>' attribute. * * @param[in] value The language of the timed text. */ void set_timed_text_language(const string& value) { _have_timed_text_language_ = true; timed_text_language_ = value; } /** * Clears the '<code>timedTextTrackName</code>' attribute so it is no longer * set. */ void clear_timed_text_track_name() { _have_timed_text_track_name_ = false; client::ClearCppValueHelper(&timed_text_track_name_); } /** * Gets the optional '<code>timedTextTrackName</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_timed_text_track_name() const { return timed_text_track_name_; } /** * Gets a modifiable pointer to the optional * <code>timedTextTrackName</code>' attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_timedTextTrackName() { _have_timed_text_track_name_ = true; return &timed_text_track_name_; } /** * Sets the '<code>timedTextTrackName</code>' attribute. * * @param[in] value The timed text track name. */ void set_timed_text_track_name(const string& value) { _have_timed_text_track_name_ = true; timed_text_track_name_ = value; } /** * Clears the '<code>updateViewedDate</code>' attribute so it is no longer * set. */ void clear_update_viewed_date() { _have_update_viewed_date_ = false; client::ClearCppValueHelper(&update_viewed_date_); } /** * Gets the optional '<code>updateViewedDate</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_update_viewed_date() const { return update_viewed_date_; } /** * Sets the '<code>updateViewedDate</code>' attribute. * * @param[in] value Whether to update the view date after successfully * updating the file. */ void set_update_viewed_date(bool value) { _have_update_viewed_date_ = true; update_viewed_date_ = value; } /** * Clears the '<code>useContentAsIndexableText</code>' attribute so it is no * longer set. */ void clear_use_content_as_indexable_text() { _have_use_content_as_indexable_text_ = false; client::ClearCppValueHelper(&use_content_as_indexable_text_); } /** * Gets the optional '<code>useContentAsIndexableText</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_use_content_as_indexable_text() const { return use_content_as_indexable_text_; } /** * Sets the '<code>useContentAsIndexableText</code>' attribute. * * @param[in] value Whether to use the content as indexable text. */ void set_use_content_as_indexable_text(bool value) { _have_use_content_as_indexable_text_ = true; use_content_as_indexable_text_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( File* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } /** * Returns MediaUploader for uploading the content. */ /** * Returns the specification for media upload using the simple protocol. */ static const client::MediaUploadSpec SIMPLE_MEDIA_UPLOAD; /** * Returns the specification for media upload using the resumable protocol. */ static const client::MediaUploadSpec RESUMABLE_MEDIA_UPLOAD; private: string file_id_; string add_parents_; bool convert_; string modified_date_behavior_; bool new_revision_; bool ocr_; string ocr_language_; bool pinned_; string remove_parents_; bool set_modified_date_; bool supports_team_drives_; string timed_text_language_; string timed_text_track_name_; bool update_viewed_date_; bool use_content_as_indexable_text_; bool _have_add_parents_ : 1; bool _have_convert_ : 1; bool _have_modified_date_behavior_ : 1; bool _have_new_revision_ : 1; bool _have_ocr_ : 1; bool _have_ocr_language_ : 1; bool _have_pinned_ : 1; bool _have_remove_parents_ : 1; bool _have_set_modified_date_ : 1; bool _have_supports_team_drives_ : 1; bool _have_timed_text_language_ : 1; bool _have_timed_text_track_name_ : 1; bool _have_update_viewed_date_ : 1; bool _have_use_content_as_indexable_text_ : 1; DISALLOW_COPY_AND_ASSIGN(FilesResource_UpdateMethod); }; /** * Implements the watch method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class FilesResource_WatchMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID for the file in question. * @param[in] _content_ The data object to watch. */ FilesResource_WatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Channel& _content_); /** * Standard destructor. */ virtual ~FilesResource_WatchMethod(); /** * Clears the '<code>acknowledgeAbuse</code>' attribute so it is no longer * set. */ void clear_acknowledge_abuse() { _have_acknowledge_abuse_ = false; client::ClearCppValueHelper(&acknowledge_abuse_); } /** * Gets the optional '<code>acknowledgeAbuse</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_acknowledge_abuse() const { return acknowledge_abuse_; } /** * Sets the '<code>acknowledgeAbuse</code>' attribute. * * @param[in] value Whether the user is acknowledging the risk of * downloading known malware or other abusive files. */ void set_acknowledge_abuse(bool value) { _have_acknowledge_abuse_ = true; acknowledge_abuse_ = value; } /** * Clears the '<code>projection</code>' attribute so it is no longer set. */ void clear_projection() { _have_projection_ = false; client::ClearCppValueHelper(&projection_); } /** * Gets the optional '<code>projection</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_projection() const { return projection_; } /** * Gets a modifiable pointer to the optional <code>projection</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_projection() { _have_projection_ = true; return &projection_; } /** * Sets the '<code>projection</code>' attribute. * * @param[in] value This parameter is deprecated and has no function. */ void set_projection(const string& value) { _have_projection_ = true; projection_ = value; } /** * Clears the '<code>revisionId</code>' attribute so it is no longer set. */ void clear_revision_id() { _have_revision_id_ = false; client::ClearCppValueHelper(&revision_id_); } /** * Gets the optional '<code>revisionId</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_revision_id() const { return revision_id_; } /** * Gets a modifiable pointer to the optional <code>revisionId</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_revisionId() { _have_revision_id_ = true; return &revision_id_; } /** * Sets the '<code>revisionId</code>' attribute. * * @param[in] value Specifies the Revision ID that should be downloaded. * Ignored unless alt=media is specified. */ void set_revision_id(const string& value) { _have_revision_id_ = true; revision_id_ = value; } /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Clears the '<code>updateViewedDate</code>' attribute so it is no longer * set. */ void clear_update_viewed_date() { _have_update_viewed_date_ = false; client::ClearCppValueHelper(&update_viewed_date_); } /** * Gets the optional '<code>updateViewedDate</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_update_viewed_date() const { return update_viewed_date_; } /** * Sets the '<code>updateViewedDate</code>' attribute. * @deprecated * * @param[in] value Deprecated: Use files.update with * modifiedDateBehavior=noChange, updateViewedDate=true and an empty request * body. */ void set_update_viewed_date(bool value) { _have_update_viewed_date_ = true; update_viewed_date_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Channel* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } /** * Determine if the request should use Media Download for the response. * * @return true for media download, false otherwise. */ bool get_use_media_download() const { return DriveServiceBaseRequest::get_use_media_download(); } /** * Sets whether Media Download should be used for the response data. * * @param[in] use true to use media download, false otherwise. */ void set_use_media_download(bool use) { DriveServiceBaseRequest::set_use_media_download(use); } private: string file_id_; bool acknowledge_abuse_; string projection_; string revision_id_; bool supports_team_drives_; bool update_viewed_date_; bool _have_acknowledge_abuse_ : 1; bool _have_projection_ : 1; bool _have_revision_id_ : 1; bool _have_supports_team_drives_ : 1; bool _have_update_viewed_date_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(FilesResource_WatchMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file */ class ParentsResource_DeleteMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] parent_id The ID of the parent. */ ParentsResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& parent_id); /** * Standard destructor. */ virtual ~ParentsResource_DeleteMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); private: string file_id_; string parent_id_; DISALLOW_COPY_AND_ASSIGN(ParentsResource_DeleteMethod); }; /** * Implements the get method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class ParentsResource_GetMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] parent_id The ID of the parent. */ ParentsResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& parent_id); /** * Standard destructor. */ virtual ~ParentsResource_GetMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( ParentReference* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string parent_id_; DISALLOW_COPY_AND_ASSIGN(ParentsResource_GetMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file */ class ParentsResource_InsertMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] _content_ The data object to insert. */ ParentsResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const ParentReference& _content_); /** * Standard destructor. */ virtual ~ParentsResource_InsertMethod(); /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( ParentReference* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; bool supports_team_drives_; bool _have_supports_team_drives_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(ParentsResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class ParentsResource_ListMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. */ ParentsResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id); /** * Standard destructor. */ virtual ~ParentsResource_ListMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( ParentList* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; DISALLOW_COPY_AND_ASSIGN(ParentsResource_ListMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file */ class PermissionsResource_DeleteMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID for the file or Team Drive. * @param[in] permission_id The ID for the permission. */ PermissionsResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id); /** * Standard destructor. */ virtual ~PermissionsResource_DeleteMethod(); /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string file_id_; string permission_id_; bool supports_team_drives_; bool _have_supports_team_drives_ : 1; DISALLOW_COPY_AND_ASSIGN(PermissionsResource_DeleteMethod); }; /** * Implements the get method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class PermissionsResource_GetMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID for the file or Team Drive. * @param[in] permission_id The ID for the permission. */ PermissionsResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id); /** * Standard destructor. */ virtual ~PermissionsResource_GetMethod(); /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Permission* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string permission_id_; bool supports_team_drives_; bool _have_supports_team_drives_ : 1; DISALLOW_COPY_AND_ASSIGN(PermissionsResource_GetMethod); }; /** * Implements the getIdForEmail method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.apps.readonly * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class PermissionsResource_GetIdForEmailMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] email The email address for which to return a permission ID. */ PermissionsResource_GetIdForEmailMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& email); /** * Standard destructor. */ virtual ~PermissionsResource_GetIdForEmailMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( PermissionId* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string email_; DISALLOW_COPY_AND_ASSIGN(PermissionsResource_GetIdForEmailMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file */ class PermissionsResource_InsertMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID for the file or Team Drive. * @param[in] _content_ The data object to insert. */ PermissionsResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Permission& _content_); /** * Standard destructor. */ virtual ~PermissionsResource_InsertMethod(); /** * Clears the '<code>emailMessage</code>' attribute so it is no longer set. */ void clear_email_message() { _have_email_message_ = false; client::ClearCppValueHelper(&email_message_); } /** * Gets the optional '<code>emailMessage</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_email_message() const { return email_message_; } /** * Gets a modifiable pointer to the optional <code>emailMessage</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_emailMessage() { _have_email_message_ = true; return &email_message_; } /** * Sets the '<code>emailMessage</code>' attribute. * * @param[in] value A custom message to include in notification emails. */ void set_email_message(const string& value) { _have_email_message_ = true; email_message_ = value; } /** * Clears the '<code>sendNotificationEmails</code>' attribute so it is no * longer set. */ void clear_send_notification_emails() { _have_send_notification_emails_ = false; client::ClearCppValueHelper(&send_notification_emails_); } /** * Gets the optional '<code>sendNotificationEmails</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_send_notification_emails() const { return send_notification_emails_; } /** * Sets the '<code>sendNotificationEmails</code>' attribute. * * @param[in] value Whether to send notification emails when sharing to * users or groups. This parameter is ignored and an email is sent if the * role is owner. */ void set_send_notification_emails(bool value) { _have_send_notification_emails_ = true; send_notification_emails_ = value; } /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Permission* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string email_message_; bool send_notification_emails_; bool supports_team_drives_; bool _have_email_message_ : 1; bool _have_send_notification_emails_ : 1; bool _have_supports_team_drives_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(PermissionsResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class PermissionsResource_ListMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID for the file or Team Drive. */ PermissionsResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id); /** * Standard destructor. */ virtual ~PermissionsResource_ListMethod(); /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ int32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maximum number of permissions to return per page. * When not set for files in a Team Drive, at most 100 results will be * returned. When not set for files that are not in a Team Drive, the entire * list will be returned. */ void set_max_results(int32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The token for continuing a previous list request on the * next page. This should be set to the value of 'nextPageToken' from the * previous response. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( PermissionList* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; int32 max_results_; string page_token_; bool supports_team_drives_; bool _have_max_results_ : 1; bool _have_page_token_ : 1; bool _have_supports_team_drives_ : 1; DISALLOW_COPY_AND_ASSIGN(PermissionsResource_ListMethod); }; typedef client::ServiceRequestPager< PermissionsResource_ListMethod, PermissionList> PermissionsResource_ListMethodPager; /** * Implements the patch method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file */ class PermissionsResource_PatchMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID for the file or Team Drive. * @param[in] permission_id The ID for the permission. * @param[in] _content_ The data object to patch. */ PermissionsResource_PatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id, const Permission& _content_); /** * Standard destructor. */ virtual ~PermissionsResource_PatchMethod(); /** * Clears the '<code>removeExpiration</code>' attribute so it is no longer * set. */ void clear_remove_expiration() { _have_remove_expiration_ = false; client::ClearCppValueHelper(&remove_expiration_); } /** * Gets the optional '<code>removeExpiration</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_remove_expiration() const { return remove_expiration_; } /** * Sets the '<code>removeExpiration</code>' attribute. * * @param[in] value Whether to remove the expiration date. */ void set_remove_expiration(bool value) { _have_remove_expiration_ = true; remove_expiration_ = value; } /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Clears the '<code>transferOwnership</code>' attribute so it is no longer * set. */ void clear_transfer_ownership() { _have_transfer_ownership_ = false; client::ClearCppValueHelper(&transfer_ownership_); } /** * Gets the optional '<code>transferOwnership</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_transfer_ownership() const { return transfer_ownership_; } /** * Sets the '<code>transferOwnership</code>' attribute. * * @param[in] value Whether changing a role to 'owner' downgrades the * current owners to writers. Does nothing if the specified role is not * 'owner'. */ void set_transfer_ownership(bool value) { _have_transfer_ownership_ = true; transfer_ownership_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Permission* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string permission_id_; bool remove_expiration_; bool supports_team_drives_; bool transfer_ownership_; bool _have_remove_expiration_ : 1; bool _have_supports_team_drives_ : 1; bool _have_transfer_ownership_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(PermissionsResource_PatchMethod); }; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file */ class PermissionsResource_UpdateMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID for the file or Team Drive. * @param[in] permission_id The ID for the permission. * @param[in] _content_ The data object to update. */ PermissionsResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id, const Permission& _content_); /** * Standard destructor. */ virtual ~PermissionsResource_UpdateMethod(); /** * Clears the '<code>removeExpiration</code>' attribute so it is no longer * set. */ void clear_remove_expiration() { _have_remove_expiration_ = false; client::ClearCppValueHelper(&remove_expiration_); } /** * Gets the optional '<code>removeExpiration</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_remove_expiration() const { return remove_expiration_; } /** * Sets the '<code>removeExpiration</code>' attribute. * * @param[in] value Whether to remove the expiration date. */ void set_remove_expiration(bool value) { _have_remove_expiration_ = true; remove_expiration_ = value; } /** * Clears the '<code>supportsTeamDrives</code>' attribute so it is no longer * set. */ void clear_supports_team_drives() { _have_supports_team_drives_ = false; client::ClearCppValueHelper(&supports_team_drives_); } /** * Gets the optional '<code>supportsTeamDrives</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_supports_team_drives() const { return supports_team_drives_; } /** * Sets the '<code>supportsTeamDrives</code>' attribute. * * @param[in] value Whether the requesting application supports Team Drives. */ void set_supports_team_drives(bool value) { _have_supports_team_drives_ = true; supports_team_drives_ = value; } /** * Clears the '<code>transferOwnership</code>' attribute so it is no longer * set. */ void clear_transfer_ownership() { _have_transfer_ownership_ = false; client::ClearCppValueHelper(&transfer_ownership_); } /** * Gets the optional '<code>transferOwnership</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_transfer_ownership() const { return transfer_ownership_; } /** * Sets the '<code>transferOwnership</code>' attribute. * * @param[in] value Whether changing a role to 'owner' downgrades the * current owners to writers. Does nothing if the specified role is not * 'owner'. */ void set_transfer_ownership(bool value) { _have_transfer_ownership_ = true; transfer_ownership_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Permission* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string permission_id_; bool remove_expiration_; bool supports_team_drives_; bool transfer_ownership_; bool _have_remove_expiration_ : 1; bool _have_supports_team_drives_ : 1; bool _have_transfer_ownership_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(PermissionsResource_UpdateMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata */ class PropertiesResource_DeleteMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] property_key The key of the property. */ PropertiesResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key); /** * Standard destructor. */ virtual ~PropertiesResource_DeleteMethod(); /** * Clears the '<code>visibility</code>' attribute so it is no longer set. */ void clear_visibility() { _have_visibility_ = false; client::ClearCppValueHelper(&visibility_); } /** * Gets the optional '<code>visibility</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_visibility() const { return visibility_; } /** * Gets a modifiable pointer to the optional <code>visibility</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_visibility() { _have_visibility_ = true; return &visibility_; } /** * Sets the '<code>visibility</code>' attribute. * * @param[in] value The visibility of the property. */ void set_visibility(const string& value) { _have_visibility_ = true; visibility_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); private: string file_id_; string property_key_; string visibility_; bool _have_visibility_ : 1; DISALLOW_COPY_AND_ASSIGN(PropertiesResource_DeleteMethod); }; /** * Implements the get method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class PropertiesResource_GetMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] property_key The key of the property. */ PropertiesResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key); /** * Standard destructor. */ virtual ~PropertiesResource_GetMethod(); /** * Clears the '<code>visibility</code>' attribute so it is no longer set. */ void clear_visibility() { _have_visibility_ = false; client::ClearCppValueHelper(&visibility_); } /** * Gets the optional '<code>visibility</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_visibility() const { return visibility_; } /** * Gets a modifiable pointer to the optional <code>visibility</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_visibility() { _have_visibility_ = true; return &visibility_; } /** * Sets the '<code>visibility</code>' attribute. * * @param[in] value The visibility of the property. */ void set_visibility(const string& value) { _have_visibility_ = true; visibility_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Property* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string property_key_; string visibility_; bool _have_visibility_ : 1; DISALLOW_COPY_AND_ASSIGN(PropertiesResource_GetMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata */ class PropertiesResource_InsertMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] _content_ The data object to insert. */ PropertiesResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Property& _content_); /** * Standard destructor. */ virtual ~PropertiesResource_InsertMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Property* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string _content_; DISALLOW_COPY_AND_ASSIGN(PropertiesResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class PropertiesResource_ListMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. */ PropertiesResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id); /** * Standard destructor. */ virtual ~PropertiesResource_ListMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( PropertyList* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; DISALLOW_COPY_AND_ASSIGN(PropertiesResource_ListMethod); }; /** * Implements the patch method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata */ class PropertiesResource_PatchMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] property_key The key of the property. * @param[in] _content_ The data object to patch. */ PropertiesResource_PatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key, const Property& _content_); /** * Standard destructor. */ virtual ~PropertiesResource_PatchMethod(); /** * Clears the '<code>visibility</code>' attribute so it is no longer set. */ void clear_visibility() { _have_visibility_ = false; client::ClearCppValueHelper(&visibility_); } /** * Gets the optional '<code>visibility</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_visibility() const { return visibility_; } /** * Gets a modifiable pointer to the optional <code>visibility</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_visibility() { _have_visibility_ = true; return &visibility_; } /** * Sets the '<code>visibility</code>' attribute. * * @param[in] value The visibility of the property. */ void set_visibility(const string& value) { _have_visibility_ = true; visibility_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Property* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string property_key_; string visibility_; bool _have_visibility_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(PropertiesResource_PatchMethod); }; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata */ class PropertiesResource_UpdateMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] property_key The key of the property. * @param[in] _content_ The data object to update. */ PropertiesResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key, const Property& _content_); /** * Standard destructor. */ virtual ~PropertiesResource_UpdateMethod(); /** * Clears the '<code>visibility</code>' attribute so it is no longer set. */ void clear_visibility() { _have_visibility_ = false; client::ClearCppValueHelper(&visibility_); } /** * Gets the optional '<code>visibility</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_visibility() const { return visibility_; } /** * Gets a modifiable pointer to the optional <code>visibility</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_visibility() { _have_visibility_ = true; return &visibility_; } /** * Sets the '<code>visibility</code>' attribute. * * @param[in] value The visibility of the property. */ void set_visibility(const string& value) { _have_visibility_ = true; visibility_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Property* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string property_key_; string visibility_; bool _have_visibility_ : 1; string _content_; DISALLOW_COPY_AND_ASSIGN(PropertiesResource_UpdateMethod); }; /** * Implements the get method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.readonly */ class RealtimeResource_GetMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file that the Realtime API data model is * associated with. */ RealtimeResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id); /** * Standard destructor. */ virtual ~RealtimeResource_GetMethod(); /** * Clears the '<code>revision</code>' attribute so it is no longer set. */ void clear_revision() { _have_revision_ = false; client::ClearCppValueHelper(&revision_); } /** * Gets the optional '<code>revision</code>' attribute. * * If the value is not set then the default value will be returned. */ int32 get_revision() const { return revision_; } /** * Sets the '<code>revision</code>' attribute. * * @param[in] value The revision of the Realtime API data model to export. * Revisions start at 1 (the initial empty data model) and are incremented * with each change. If this parameter is excluded, the most recent data * model will be returned. */ void set_revision(int32 value) { _have_revision_ = true; revision_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Determine if the request should use Media Download for the response. * * @return true for media download, false otherwise. */ bool get_use_media_download() const { return DriveServiceBaseRequest::get_use_media_download(); } /** * Sets whether Media Download should be used for the response data. * * @param[in] use true to use media download, false otherwise. */ void set_use_media_download(bool use) { DriveServiceBaseRequest::set_use_media_download(use); } private: string file_id_; int32 revision_; bool _have_revision_ : 1; DISALLOW_COPY_AND_ASSIGN(RealtimeResource_GetMethod); }; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file */ class RealtimeResource_UpdateMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file that the Realtime API data model is * associated with. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to update. If * this is NULL then do not upload any media and ignore * _media_content_type_. */ RealtimeResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_); /** * Standard destructor. */ virtual ~RealtimeResource_UpdateMethod(); /** * Clears the '<code>baseRevision</code>' attribute so it is no longer set. */ void clear_base_revision() { _have_base_revision_ = false; client::ClearCppValueHelper(&base_revision_); } /** * Gets the optional '<code>baseRevision</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_base_revision() const { return base_revision_; } /** * Gets a modifiable pointer to the optional <code>baseRevision</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_baseRevision() { _have_base_revision_ = true; return &base_revision_; } /** * Sets the '<code>baseRevision</code>' attribute. * * @param[in] value The revision of the model to diff the uploaded model * against. If set, the uploaded model is diffed against the provided * revision and those differences are merged with any changes made to the * model after the provided revision. If not set, the uploaded model * replaces the current model on the server. */ void set_base_revision(const string& value) { _have_base_revision_ = true; base_revision_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Returns MediaUploader for uploading the content. */ /** * Returns the specification for media upload using the simple protocol. */ static const client::MediaUploadSpec SIMPLE_MEDIA_UPLOAD; /** * Returns the specification for media upload using the resumable protocol. */ static const client::MediaUploadSpec RESUMABLE_MEDIA_UPLOAD; private: string file_id_; string base_revision_; bool _have_base_revision_ : 1; DISALLOW_COPY_AND_ASSIGN(RealtimeResource_UpdateMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file */ class RepliesResource_DeleteMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @param[in] reply_id The ID of the reply. */ RepliesResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id); /** * Standard destructor. */ virtual ~RepliesResource_DeleteMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); private: string file_id_; string comment_id_; string reply_id_; DISALLOW_COPY_AND_ASSIGN(RepliesResource_DeleteMethod); }; /** * Implements the get method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.readonly */ class RepliesResource_GetMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @param[in] reply_id The ID of the reply. */ RepliesResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id); /** * Standard destructor. */ virtual ~RepliesResource_GetMethod(); /** * Clears the '<code>includeDeleted</code>' attribute so it is no longer * set. */ void clear_include_deleted() { _have_include_deleted_ = false; client::ClearCppValueHelper(&include_deleted_); } /** * Gets the optional '<code>includeDeleted</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_include_deleted() const { return include_deleted_; } /** * Sets the '<code>includeDeleted</code>' attribute. * * @param[in] value If set, this will succeed when retrieving a deleted * reply. */ void set_include_deleted(bool value) { _have_include_deleted_ = true; include_deleted_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( CommentReply* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string comment_id_; string reply_id_; bool include_deleted_; bool _have_include_deleted_ : 1; DISALLOW_COPY_AND_ASSIGN(RepliesResource_GetMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file */ class RepliesResource_InsertMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @param[in] _content_ The data object to insert. */ RepliesResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const CommentReply& _content_); /** * Standard destructor. */ virtual ~RepliesResource_InsertMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( CommentReply* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string comment_id_; string _content_; DISALLOW_COPY_AND_ASSIGN(RepliesResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.readonly */ class RepliesResource_ListMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. */ RepliesResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id); /** * Standard destructor. */ virtual ~RepliesResource_ListMethod(); /** * Clears the '<code>includeDeleted</code>' attribute so it is no longer * set. */ void clear_include_deleted() { _have_include_deleted_ = false; client::ClearCppValueHelper(&include_deleted_); } /** * Gets the optional '<code>includeDeleted</code>' attribute. * * If the value is not set then the default value will be returned. */ bool get_include_deleted() const { return include_deleted_; } /** * Sets the '<code>includeDeleted</code>' attribute. * * @param[in] value If set, all replies, including deleted replies (with * content stripped) will be returned. */ void set_include_deleted(bool value) { _have_include_deleted_ = true; include_deleted_ = value; } /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ int32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value The maximum number of replies to include in the * response, used for paging. */ void set_max_results(int32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value The continuation token, used to page through large * result sets. To get the next page of results, set this parameter to the * value of "nextPageToken" from the previous response. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( CommentReplyList* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string comment_id_; bool include_deleted_; int32 max_results_; string page_token_; bool _have_include_deleted_ : 1; bool _have_max_results_ : 1; bool _have_page_token_ : 1; DISALLOW_COPY_AND_ASSIGN(RepliesResource_ListMethod); }; typedef client::ServiceRequestPager< RepliesResource_ListMethod, CommentReplyList> RepliesResource_ListMethodPager; /** * Implements the patch method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file */ class RepliesResource_PatchMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @param[in] reply_id The ID of the reply. * @param[in] _content_ The data object to patch. */ RepliesResource_PatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id, const CommentReply& _content_); /** * Standard destructor. */ virtual ~RepliesResource_PatchMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( CommentReply* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string comment_id_; string reply_id_; string _content_; DISALLOW_COPY_AND_ASSIGN(RepliesResource_PatchMethod); }; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.file */ class RepliesResource_UpdateMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @param[in] reply_id The ID of the reply. * @param[in] _content_ The data object to update. */ RepliesResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id, const CommentReply& _content_); /** * Standard destructor. */ virtual ~RepliesResource_UpdateMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( CommentReply* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string comment_id_; string reply_id_; string _content_; DISALLOW_COPY_AND_ASSIGN(RepliesResource_UpdateMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file */ class RevisionsResource_DeleteMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] revision_id The ID of the revision. */ RevisionsResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id); /** * Standard destructor. */ virtual ~RevisionsResource_DeleteMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); private: string file_id_; string revision_id_; DISALLOW_COPY_AND_ASSIGN(RevisionsResource_DeleteMethod); }; /** * Implements the get method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class RevisionsResource_GetMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. * @param[in] revision_id The ID of the revision. */ RevisionsResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id); /** * Standard destructor. */ virtual ~RevisionsResource_GetMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Revision* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string revision_id_; DISALLOW_COPY_AND_ASSIGN(RevisionsResource_GetMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file * https://www.googleapis.com/auth/drive.metadata * https://www.googleapis.com/auth/drive.metadata.readonly * https://www.googleapis.com/auth/drive.photos.readonly * https://www.googleapis.com/auth/drive.readonly */ class RevisionsResource_ListMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID of the file. */ RevisionsResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id); /** * Standard destructor. */ virtual ~RevisionsResource_ListMethod(); /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ int32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value Maximum number of revisions to return. */ void set_max_results(int32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value Page token for revisions. To get the next page of * results, set this parameter to the value of "nextPageToken" from the * previous response. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( RevisionList* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; int32 max_results_; string page_token_; bool _have_max_results_ : 1; bool _have_page_token_ : 1; DISALLOW_COPY_AND_ASSIGN(RevisionsResource_ListMethod); }; typedef client::ServiceRequestPager< RevisionsResource_ListMethod, RevisionList> RevisionsResource_ListMethodPager; /** * Implements the patch method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file */ class RevisionsResource_PatchMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID for the file. * @param[in] revision_id The ID for the revision. * @param[in] _content_ The data object to patch. */ RevisionsResource_PatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id, const Revision& _content_); /** * Standard destructor. */ virtual ~RevisionsResource_PatchMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Revision* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string revision_id_; string _content_; DISALLOW_COPY_AND_ASSIGN(RevisionsResource_PatchMethod); }; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.appdata * https://www.googleapis.com/auth/drive.file */ class RevisionsResource_UpdateMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] file_id The ID for the file. * @param[in] revision_id The ID for the revision. * @param[in] _content_ The data object to update. */ RevisionsResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id, const Revision& _content_); /** * Standard destructor. */ virtual ~RevisionsResource_UpdateMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( Revision* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string file_id_; string revision_id_; string _content_; DISALLOW_COPY_AND_ASSIGN(RevisionsResource_UpdateMethod); }; /** * Implements the delete method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive */ class TeamdrivesResource_DeleteMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] team_drive_id The ID of the Team Drive. */ TeamdrivesResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& team_drive_id); /** * Standard destructor. */ virtual ~TeamdrivesResource_DeleteMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); private: string team_drive_id_; DISALLOW_COPY_AND_ASSIGN(TeamdrivesResource_DeleteMethod); }; /** * Implements the get method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.readonly */ class TeamdrivesResource_GetMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] team_drive_id The ID of the Team Drive. */ TeamdrivesResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& team_drive_id); /** * Standard destructor. */ virtual ~TeamdrivesResource_GetMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( TeamDrive* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string team_drive_id_; DISALLOW_COPY_AND_ASSIGN(TeamdrivesResource_GetMethod); }; /** * Implements the insert method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive */ class TeamdrivesResource_InsertMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] request_id An ID, such as a random UUID, which uniquely * identifies this user's request for idempotent creation of a Team Drive. A * repeated request by the same user and with the same request ID will avoid * creating duplicates by attempting to create the same Team Drive. If the * Team Drive already exists a 409 error will be returned. * @param[in] _content_ The data object to insert. */ TeamdrivesResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& request_id, const TeamDrive& _content_); /** * Standard destructor. */ virtual ~TeamdrivesResource_InsertMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( TeamDrive* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string request_id_; string _content_; DISALLOW_COPY_AND_ASSIGN(TeamdrivesResource_InsertMethod); }; /** * Implements the list method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive * https://www.googleapis.com/auth/drive.readonly */ class TeamdrivesResource_ListMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. */ TeamdrivesResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_); /** * Standard destructor. */ virtual ~TeamdrivesResource_ListMethod(); /** * Clears the '<code>maxResults</code>' attribute so it is no longer set. */ void clear_max_results() { _have_max_results_ = false; client::ClearCppValueHelper(&max_results_); } /** * Gets the optional '<code>maxResults</code>' attribute. * * If the value is not set then the default value will be returned. */ int32 get_max_results() const { return max_results_; } /** * Sets the '<code>maxResults</code>' attribute. * * @param[in] value Maximum number of Team Drives to return. */ void set_max_results(int32 value) { _have_max_results_ = true; max_results_ = value; } /** * Clears the '<code>pageToken</code>' attribute so it is no longer set. */ void clear_page_token() { _have_page_token_ = false; client::ClearCppValueHelper(&page_token_); } /** * Gets the optional '<code>pageToken</code>' attribute. * * If the value is not set then the default value will be returned. */ const string& get_page_token() const { return page_token_; } /** * Gets a modifiable pointer to the optional <code>pageToken</code>' * attribute. * * @return The value can be set by dereferencing the pointer. */ string* mutable_pageToken() { _have_page_token_ = true; return &page_token_; } /** * Sets the '<code>pageToken</code>' attribute. * * @param[in] value Page token for Team Drives. */ void set_page_token(const string& value) { _have_page_token_ = true; page_token_ = value; } /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Appends the optional query parameters to the target URL. * * @param[in, out] target The URL string to append to. */ virtual util::Status AppendOptionalQueryParameters(string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( TeamDriveList* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: int32 max_results_; string page_token_; bool _have_max_results_ : 1; bool _have_page_token_ : 1; DISALLOW_COPY_AND_ASSIGN(TeamdrivesResource_ListMethod); }; typedef client::ServiceRequestPager< TeamdrivesResource_ListMethod, TeamDriveList> TeamdrivesResource_ListMethodPager; /** * Implements the update method. * * @ingroup ServiceMethod * * This class uses the Command Pattern. Construct an instance with the required * parameters, then set any additional optional parameters by using the * attribute setters. To invoke the method, call <code>Execute</code>. * * One or more of these authorization scopes are required for this method: * https://www.googleapis.com/auth/drive */ class TeamdrivesResource_UpdateMethod : public DriveServiceBaseRequest { public: /** * The standard constructor takes all the required method parameters. * @param[in] _service_ The service instance to send to when executed. * @param[in] _credential_ If not NULL, the credential to authorize with. * In practice this is supplied by the user code that is * creating the method instance. * @param[in] team_drive_id The ID of the Team Drive. * @param[in] _content_ The data object to update. */ TeamdrivesResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& team_drive_id, const TeamDrive& _content_); /** * Standard destructor. */ virtual ~TeamdrivesResource_UpdateMethod(); /** * Appends variable value to the target string. * * This is a helper function used to resolve templated variables in the URI. * * @param[in] variable_name The name of the templated variable. * @param[in] config A pass-through parameter used for lists and maps. * @param[in, out] target The string to append the value to. */ virtual util::Status AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target); /** * Executes the method and parses the response into a data object on success. * * @param[out] data Loads from the response payload JSON data on success. * * @return Success if an HTTP 2xx response was received. Otherwise the * status indicates the reason for failure. Finer detail may be * available from the underlying http_request to distinguish the * transport_status from the overal HTTP request status. */ util::Status ExecuteAndParseResponse( TeamDrive* data) { return DriveServiceBaseRequest::ExecuteAndParseResponse(data); } private: string team_drive_id_; string _content_; DISALLOW_COPY_AND_ASSIGN(TeamdrivesResource_UpdateMethod); }; /** * Service definition for DriveService (v2). * * @ingroup ServiceClass * * For more information about this service, see the API Documentation at * <a href='https://developers.google.com/drive/'>'https://developers.google.com/drive/</a> */ class DriveService : public client::ClientService { public: /** * The name of the API that this was generated from. */ static const char googleapis_API_NAME[]; /** * The version of the API that this interface was generated from. */ static const char googleapis_API_VERSION[]; /** * The code generator used to generate this API. */ static const char googleapis_API_GENERATOR[]; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class AboutResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit AboutResource(DriveService* service); /** * Standard destructor. */ ~AboutResource() {} /** * Creates a new AboutResource_GetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ AboutResource_GetMethod* NewGetMethod( client::AuthorizationCredential* _credential_) const; private: DriveService* service_; DISALLOW_COPY_AND_ASSIGN(AboutResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class AppsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit AppsResource(DriveService* service); /** * Standard destructor. */ ~AppsResource() {} /** * Creates a new AppsResource_GetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] app_id The ID of the app. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ AppsResource_GetMethod* NewGetMethod( client::AuthorizationCredential* _credential_, const StringPiece& app_id) const; /** * Creates a new AppsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ AppsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_) const; private: DriveService* service_; DISALLOW_COPY_AND_ASSIGN(AppsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class ChangesResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit ChangesResource(DriveService* service); /** * Standard destructor. */ ~ChangesResource() {} /** * Creates a new ChangesResource_GetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] change_id The ID of the change. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChangesResource_GetMethod* NewGetMethod( client::AuthorizationCredential* _credential_, const StringPiece& change_id) const; /** * Creates a new ChangesResource_GetStartPageTokenMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChangesResource_GetStartPageTokenMethod* NewGetStartPageTokenMethod( client::AuthorizationCredential* _credential_) const; /** * Creates a new ChangesResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChangesResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * * @see googleapis::googleapis::ServiceRequestPager */ ChangesResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_) const; /** * Creates a new ChangesResource_WatchMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] _content_ The data object to watch. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChangesResource_WatchMethod* NewWatchMethod( client::AuthorizationCredential* _credential_, const Channel& _content_) const; private: DriveService* service_; DISALLOW_COPY_AND_ASSIGN(ChangesResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class ChannelsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit ChannelsResource(DriveService* service); /** * Standard destructor. */ ~ChannelsResource() {} /** * Creates a new ChannelsResource_StopMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] _content_ The data object to stop. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChannelsResource_StopMethod* NewStopMethod( client::AuthorizationCredential* _credential_, const Channel& _content_) const; private: DriveService* service_; DISALLOW_COPY_AND_ASSIGN(ChannelsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class ChildrenResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit ChildrenResource(DriveService* service); /** * Standard destructor. */ ~ChildrenResource() {} /** * Creates a new ChildrenResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] folder_id The ID of the folder. * @param[in] child_id The ID of the child. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChildrenResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& folder_id, const StringPiece& child_id) const; /** * Creates a new ChildrenResource_GetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] folder_id The ID of the folder. * @param[in] child_id The ID of the child. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChildrenResource_GetMethod* NewGetMethod( client::AuthorizationCredential* _credential_, const StringPiece& folder_id, const StringPiece& child_id) const; /** * Creates a new ChildrenResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] folder_id The ID of the folder. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChildrenResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& folder_id, const ChildReference& _content_) const; /** * Creates a new ChildrenResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] folder_id The ID of the folder. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ChildrenResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& folder_id) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] folder_id The ID of the folder. * * * @see googleapis::googleapis::ServiceRequestPager */ ChildrenResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& folder_id) const; private: DriveService* service_; DISALLOW_COPY_AND_ASSIGN(ChildrenResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class CommentsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit CommentsResource(DriveService* service); /** * Standard destructor. */ ~CommentsResource() {} /** * Creates a new CommentsResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CommentsResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id) const; /** * Creates a new CommentsResource_GetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CommentsResource_GetMethod* NewGetMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id) const; /** * Creates a new CommentsResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CommentsResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Comment& _content_) const; /** * Creates a new CommentsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CommentsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * * * @see googleapis::googleapis::ServiceRequestPager */ CommentsResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& file_id) const; /** * Creates a new CommentsResource_PatchMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @param[in] _content_ The data object to patch. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CommentsResource_PatchMethod* NewPatchMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const Comment& _content_) const; /** * Creates a new CommentsResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @param[in] _content_ The data object to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ CommentsResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const Comment& _content_) const; private: DriveService* service_; DISALLOW_COPY_AND_ASSIGN(CommentsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class FilesResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit FilesResource(DriveService* service); /** * Standard destructor. */ ~FilesResource() {} /** * Creates a new FilesResource_CopyMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file to copy. * @param[in] _content_ The data object to copy. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_CopyMethod* NewCopyMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const File& _content_) const; /** * Creates a new FilesResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file to delete. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id) const; /** * Creates a new FilesResource_EmptyTrashMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_EmptyTrashMethod* NewEmptyTrashMethod( client::AuthorizationCredential* _credential_) const; /** * Creates a new FilesResource_ExportMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] mime_type The MIME type of the format requested for this * export. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_ExportMethod* NewExportMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& mime_type) const; /** * Creates a new FilesResource_GenerateIdsMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_GenerateIdsMethod* NewGenerateIdsMethod( client::AuthorizationCredential* _credential_) const; /** * Creates a new FilesResource_GetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID for the file in question. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_GetMethod* NewGetMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id) const; /** * Creates a new FilesResource_InsertMethod instance. * @deprecated * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_) const; /** * Creates a new FilesResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] _metadata_ The metadata object to insert. If this is NULL then * do not upload any metadata. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to insert. If * this is NULL then do not upload any media and ignore * _media_content_type_. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const File* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const; /** * Creates a new FilesResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * * @see googleapis::googleapis::ServiceRequestPager */ FilesResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_) const; /** * Creates a new FilesResource_PatchMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file to update. * @param[in] _content_ The data object to patch. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_PatchMethod* NewPatchMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const File& _content_) const; /** * Creates a new FilesResource_TouchMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_TouchMethod* NewTouchMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id) const; /** * Creates a new FilesResource_TrashMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file to trash. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_TrashMethod* NewTrashMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id) const; /** * Creates a new FilesResource_UntrashMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file to untrash. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_UntrashMethod* NewUntrashMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id) const; /** * Creates a new FilesResource_UpdateMethod instance. * @deprecated * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file to update. * * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id) const; /** * Creates a new FilesResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file to update. * @param[in] _metadata_ The metadata object to update. If this is NULL then * do not upload any metadata. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to update. If * this is NULL then do not upload any media and ignore * _media_content_type_. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const File* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const; /** * Creates a new FilesResource_WatchMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID for the file in question. * @param[in] _content_ The data object to watch. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ FilesResource_WatchMethod* NewWatchMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Channel& _content_) const; private: DriveService* service_; DISALLOW_COPY_AND_ASSIGN(FilesResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class ParentsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit ParentsResource(DriveService* service); /** * Standard destructor. */ ~ParentsResource() {} /** * Creates a new ParentsResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] parent_id The ID of the parent. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ParentsResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& parent_id) const; /** * Creates a new ParentsResource_GetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] parent_id The ID of the parent. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ParentsResource_GetMethod* NewGetMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& parent_id) const; /** * Creates a new ParentsResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ParentsResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const ParentReference& _content_) const; /** * Creates a new ParentsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ ParentsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id) const; private: DriveService* service_; DISALLOW_COPY_AND_ASSIGN(ParentsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class PermissionsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit PermissionsResource(DriveService* service); /** * Standard destructor. */ ~PermissionsResource() {} /** * Creates a new PermissionsResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID for the file or Team Drive. * @param[in] permission_id The ID for the permission. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PermissionsResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id) const; /** * Creates a new PermissionsResource_GetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID for the file or Team Drive. * @param[in] permission_id The ID for the permission. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PermissionsResource_GetMethod* NewGetMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id) const; /** * Creates a new PermissionsResource_GetIdForEmailMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] email The email address for which to return a permission ID. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PermissionsResource_GetIdForEmailMethod* NewGetIdForEmailMethod( client::AuthorizationCredential* _credential_, const StringPiece& email) const; /** * Creates a new PermissionsResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID for the file or Team Drive. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PermissionsResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Permission& _content_) const; /** * Creates a new PermissionsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID for the file or Team Drive. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PermissionsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] file_id The ID for the file or Team Drive. * * * @see googleapis::googleapis::ServiceRequestPager */ PermissionsResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& file_id) const; /** * Creates a new PermissionsResource_PatchMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID for the file or Team Drive. * @param[in] permission_id The ID for the permission. * @param[in] _content_ The data object to patch. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PermissionsResource_PatchMethod* NewPatchMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id, const Permission& _content_) const; /** * Creates a new PermissionsResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID for the file or Team Drive. * @param[in] permission_id The ID for the permission. * @param[in] _content_ The data object to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PermissionsResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id, const Permission& _content_) const; private: DriveService* service_; DISALLOW_COPY_AND_ASSIGN(PermissionsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class PropertiesResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit PropertiesResource(DriveService* service); /** * Standard destructor. */ ~PropertiesResource() {} /** * Creates a new PropertiesResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] property_key The key of the property. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PropertiesResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key) const; /** * Creates a new PropertiesResource_GetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] property_key The key of the property. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PropertiesResource_GetMethod* NewGetMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key) const; /** * Creates a new PropertiesResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PropertiesResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Property& _content_) const; /** * Creates a new PropertiesResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PropertiesResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id) const; /** * Creates a new PropertiesResource_PatchMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] property_key The key of the property. * @param[in] _content_ The data object to patch. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PropertiesResource_PatchMethod* NewPatchMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key, const Property& _content_) const; /** * Creates a new PropertiesResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] property_key The key of the property. * @param[in] _content_ The data object to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ PropertiesResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key, const Property& _content_) const; private: DriveService* service_; DISALLOW_COPY_AND_ASSIGN(PropertiesResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class RealtimeResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit RealtimeResource(DriveService* service); /** * Standard destructor. */ ~RealtimeResource() {} /** * Creates a new RealtimeResource_GetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file that the Realtime API data model is * associated with. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ RealtimeResource_GetMethod* NewGetMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id) const; /** * Creates a new RealtimeResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file that the Realtime API data model is * associated with. * @param[in] _media_content_type_ The content type of the data in the * _media_content_reader_. * @param[in] _media_content_reader_ The media content to update. If * this is NULL then do not upload any media and ignore * _media_content_type_. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ RealtimeResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const; private: DriveService* service_; DISALLOW_COPY_AND_ASSIGN(RealtimeResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class RepliesResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit RepliesResource(DriveService* service); /** * Standard destructor. */ ~RepliesResource() {} /** * Creates a new RepliesResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @param[in] reply_id The ID of the reply. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ RepliesResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id) const; /** * Creates a new RepliesResource_GetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @param[in] reply_id The ID of the reply. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ RepliesResource_GetMethod* NewGetMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id) const; /** * Creates a new RepliesResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ RepliesResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const CommentReply& _content_) const; /** * Creates a new RepliesResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ RepliesResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * * @param[in] comment_id The ID of the comment. * * * @see googleapis::googleapis::ServiceRequestPager */ RepliesResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id) const; /** * Creates a new RepliesResource_PatchMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @param[in] reply_id The ID of the reply. * @param[in] _content_ The data object to patch. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ RepliesResource_PatchMethod* NewPatchMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id, const CommentReply& _content_) const; /** * Creates a new RepliesResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] comment_id The ID of the comment. * @param[in] reply_id The ID of the reply. * @param[in] _content_ The data object to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ RepliesResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id, const CommentReply& _content_) const; private: DriveService* service_; DISALLOW_COPY_AND_ASSIGN(RepliesResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class RevisionsResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit RevisionsResource(DriveService* service); /** * Standard destructor. */ ~RevisionsResource() {} /** * Creates a new RevisionsResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] revision_id The ID of the revision. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ RevisionsResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id) const; /** * Creates a new RevisionsResource_GetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @param[in] revision_id The ID of the revision. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ RevisionsResource_GetMethod* NewGetMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id) const; /** * Creates a new RevisionsResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ RevisionsResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * @param[in] file_id The ID of the file. * * * @see googleapis::googleapis::ServiceRequestPager */ RevisionsResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_, const StringPiece& file_id) const; /** * Creates a new RevisionsResource_PatchMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID for the file. * @param[in] revision_id The ID for the revision. * @param[in] _content_ The data object to patch. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ RevisionsResource_PatchMethod* NewPatchMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id, const Revision& _content_) const; /** * Creates a new RevisionsResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] file_id The ID for the file. * @param[in] revision_id The ID for the revision. * @param[in] _content_ The data object to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ RevisionsResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id, const Revision& _content_) const; private: DriveService* service_; DISALLOW_COPY_AND_ASSIGN(RevisionsResource); }; /** * Acts as message factory for accessing data. * * @ingroup ServiceClass */ class TeamdrivesResource { public: /** * Standard constructor. * * @param[in] service The service instance is used to bind to the * methods created from this resource instance. This will be * the service that methods are invoked on. */ explicit TeamdrivesResource(DriveService* service); /** * Standard destructor. */ ~TeamdrivesResource() {} /** * Creates a new TeamdrivesResource_DeleteMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] team_drive_id The ID of the Team Drive. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ TeamdrivesResource_DeleteMethod* NewDeleteMethod( client::AuthorizationCredential* _credential_, const StringPiece& team_drive_id) const; /** * Creates a new TeamdrivesResource_GetMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] team_drive_id The ID of the Team Drive. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ TeamdrivesResource_GetMethod* NewGetMethod( client::AuthorizationCredential* _credential_, const StringPiece& team_drive_id) const; /** * Creates a new TeamdrivesResource_InsertMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] request_id An ID, such as a random UUID, which uniquely * identifies this user's request for idempotent creation of a Team Drive. A * repeated request by the same user and with the same request ID will avoid * creating duplicates by attempting to create the same Team Drive. If the * Team Drive already exists a 409 error will be returned. * @param[in] _content_ The data object to insert. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ TeamdrivesResource_InsertMethod* NewInsertMethod( client::AuthorizationCredential* _credential_, const StringPiece& request_id, const TeamDrive& _content_) const; /** * Creates a new TeamdrivesResource_ListMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ TeamdrivesResource_ListMethod* NewListMethod( client::AuthorizationCredential* _credential_) const; /** * Creates a pager for iterating over incremental result pages. * @param[in] _credential_ NULL credentials will not authorize the request. * * @see googleapis::googleapis::ServiceRequestPager */ TeamdrivesResource_ListMethodPager* NewListMethodPager( client::AuthorizationCredential* _credential_) const; /** * Creates a new TeamdrivesResource_UpdateMethod instance. * * @param[in] _credential_ Can be NULL. * NULL credentials will not authorize the request. * @param[in] team_drive_id The ID of the Team Drive. * @param[in] _content_ The data object to update. * @returns The caller should <code>Execute</code> the method instance, * then destroy it when they are finished. */ TeamdrivesResource_UpdateMethod* NewUpdateMethod( client::AuthorizationCredential* _credential_, const StringPiece& team_drive_id, const TeamDrive& _content_) const; private: DriveService* service_; DISALLOW_COPY_AND_ASSIGN(TeamdrivesResource); }; /** * Standard constructor. * * @param[in] transport The transport to use when creating methods to invoke * on this service instance. */ explicit DriveService(client::HttpTransport* transport); /** * Standard destructor. */ virtual ~DriveService(); /** * Gets the resource method factory. * * @return AboutResource for creating methods. */ const AboutResource& get_about() const { return about_; } /** * Gets the resource method factory. * * @return AppsResource for creating methods. */ const AppsResource& get_apps() const { return apps_; } /** * Gets the resource method factory. * * @return ChangesResource for creating methods. */ const ChangesResource& get_changes() const { return changes_; } /** * Gets the resource method factory. * * @return ChannelsResource for creating methods. */ const ChannelsResource& get_channels() const { return channels_; } /** * Gets the resource method factory. * * @return ChildrenResource for creating methods. */ const ChildrenResource& get_children() const { return children_; } /** * Gets the resource method factory. * * @return CommentsResource for creating methods. */ const CommentsResource& get_comments() const { return comments_; } /** * Gets the resource method factory. * * @return FilesResource for creating methods. */ const FilesResource& get_files() const { return files_; } /** * Gets the resource method factory. * * @return ParentsResource for creating methods. */ const ParentsResource& get_parents() const { return parents_; } /** * Gets the resource method factory. * * @return PermissionsResource for creating methods. */ const PermissionsResource& get_permissions() const { return permissions_; } /** * Gets the resource method factory. * * @return PropertiesResource for creating methods. */ const PropertiesResource& get_properties() const { return properties_; } /** * Gets the resource method factory. * * @return RealtimeResource for creating methods. */ const RealtimeResource& get_realtime() const { return realtime_; } /** * Gets the resource method factory. * * @return RepliesResource for creating methods. */ const RepliesResource& get_replies() const { return replies_; } /** * Gets the resource method factory. * * @return RevisionsResource for creating methods. */ const RevisionsResource& get_revisions() const { return revisions_; } /** * Gets the resource method factory. * * @return TeamdrivesResource for creating methods. */ const TeamdrivesResource& get_teamdrives() const { return teamdrives_; } /** * Declares the OAuth2.0 scopes used within Drive API * * These scopes shoudl be used when asking for credentials to invoke methods * in the DriveService. */ class SCOPES { public: /** * View and manage the files in your Google Drive. */ static const char DRIVE[]; /** * View and manage its own configuration data in your Google Drive. */ static const char DRIVE_APPDATA[]; /** * View your Google Drive apps. */ static const char DRIVE_APPS_READONLY[]; /** * View and manage Google Drive files and folders that you have opened or * created with this app. */ static const char DRIVE_FILE[]; /** * View and manage metadata of files in your Google Drive. */ static const char DRIVE_METADATA[]; /** * View metadata for files in your Google Drive. */ static const char DRIVE_METADATA_READONLY[]; /** * View the photos, videos and albums in your Google Photos. */ static const char DRIVE_PHOTOS_READONLY[]; /** * View the files in your Google Drive. */ static const char DRIVE_READONLY[]; /** * Modify your Google Apps Script scripts' behavior. */ static const char DRIVE_SCRIPTS[]; private: SCOPES(); // Never instantiated. ~SCOPES(); // Never instantiated. }; private: AboutResource about_; AppsResource apps_; ChangesResource changes_; ChannelsResource channels_; ChildrenResource children_; CommentsResource comments_; FilesResource files_; ParentsResource parents_; PermissionsResource permissions_; PropertiesResource properties_; RealtimeResource realtime_; RepliesResource replies_; RevisionsResource revisions_; TeamdrivesResource teamdrives_; DISALLOW_COPY_AND_ASSIGN(DriveService); }; /** * @defgroup DataObject Drive API Data Objects * * The data objects are used as parameters and responses from service requests. * For more information about using data objects, see the * <a href='https://developers.google.com/api-client-library/cpp/'> * Google APIs Client Library for C++ Developers's Guide</a>. */ /** * @defgroup ServiceClass Drive API Service * * The service classes contain information about accessing and using the * Drive API cloud service. * * For more information about using services, see the * <a href='https://developers.google.com/api-client-library/cpp/'> * Google APIs Client Library for C++ Developers's Guide</a>. */ /** * @defgroup ServiceMethod Drive API Service Methods * * The service method classes are used to create and invoke methods in the * DriveService to access the Drive API. * * For more information about using services, see the * <a href='https://developers.google.com/api-client-library/cpp/'> * Google APIs Client Library for C++ Developers's Guide</a>. */ } // namespace google_drive_api #endif // GOOGLE_DRIVE_API_DRIVE_SERVICE_H_ <file_sep>/service_apis/youtube/google/youtube_api/playlist_item.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Description: // Supports core YouTube features, such as uploading videos, creating and managing playlists, searching for content, and much more. // Classes: // PlaylistItem // Documentation: // https://developers.google.com/youtube/v3 #include "google/youtube_api/playlist_item.h" #include <string> #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/playlist_item_content_details.h" #include "google/youtube_api/playlist_item_snippet.h" #include "google/youtube_api/playlist_item_status.h" #include <string> #include "googleapis/strings/strcat.h" namespace google_youtube_api { using namespace googleapis; // Object factory method (static). PlaylistItem* PlaylistItem::New() { return new client::JsonCppCapsule<PlaylistItem>; } // Standard immutable constructor. PlaylistItem::PlaylistItem(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. PlaylistItem::PlaylistItem(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. PlaylistItem::~PlaylistItem() { } // Properties. const PlaylistItemContentDetails PlaylistItem::get_content_details() const { const Json::Value& storage = Storage("contentDetails"); return client::JsonValueToCppValueHelper<PlaylistItemContentDetails >(storage); } PlaylistItemContentDetails PlaylistItem::mutable_contentDetails() { Json::Value* storage = MutableStorage("contentDetails"); return client::JsonValueToMutableCppValueHelper<PlaylistItemContentDetails >(storage); } const PlaylistItemSnippet PlaylistItem::get_snippet() const { const Json::Value& storage = Storage("snippet"); return client::JsonValueToCppValueHelper<PlaylistItemSnippet >(storage); } PlaylistItemSnippet PlaylistItem::mutable_snippet() { Json::Value* storage = MutableStorage("snippet"); return client::JsonValueToMutableCppValueHelper<PlaylistItemSnippet >(storage); } const PlaylistItemStatus PlaylistItem::get_status() const { const Json::Value& storage = Storage("status"); return client::JsonValueToCppValueHelper<PlaylistItemStatus >(storage); } PlaylistItemStatus PlaylistItem::mutable_status() { Json::Value* storage = MutableStorage("status"); return client::JsonValueToMutableCppValueHelper<PlaylistItemStatus >(storage); } } // namespace google_youtube_api <file_sep>/service_apis/youtube/google/youtube_api/playlist_item_list_response.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Description: // Supports core YouTube features, such as uploading videos, creating and managing playlists, searching for content, and much more. // Classes: // PlaylistItemListResponse // Documentation: // https://developers.google.com/youtube/v3 #include "google/youtube_api/playlist_item_list_response.h" #include <string> #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/page_info.h" #include "google/youtube_api/playlist_item.h" #include "google/youtube_api/token_pagination.h" #include <string> #include "googleapis/strings/strcat.h" namespace google_youtube_api { using namespace googleapis; // Object factory method (static). PlaylistItemListResponse* PlaylistItemListResponse::New() { return new client::JsonCppCapsule<PlaylistItemListResponse>; } // Standard immutable constructor. PlaylistItemListResponse::PlaylistItemListResponse(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. PlaylistItemListResponse::PlaylistItemListResponse(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. PlaylistItemListResponse::~PlaylistItemListResponse() { } // Properties. const client::JsonCppArray<PlaylistItem > PlaylistItemListResponse::get_items() const { const Json::Value& storage = Storage("items"); return client::JsonValueToCppValueHelper<client::JsonCppArray<PlaylistItem > >(storage); } client::JsonCppArray<PlaylistItem > PlaylistItemListResponse::mutable_items() { Json::Value* storage = MutableStorage("items"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<PlaylistItem > >(storage); } const PageInfo PlaylistItemListResponse::get_page_info() const { const Json::Value& storage = Storage("pageInfo"); return client::JsonValueToCppValueHelper<PageInfo >(storage); } PageInfo PlaylistItemListResponse::mutable_pageInfo() { Json::Value* storage = MutableStorage("pageInfo"); return client::JsonValueToMutableCppValueHelper<PageInfo >(storage); } const TokenPagination PlaylistItemListResponse::get_token_pagination() const { const Json::Value& storage = Storage("tokenPagination"); return client::JsonValueToCppValueHelper<TokenPagination >(storage); } TokenPagination PlaylistItemListResponse::mutable_tokenPagination() { Json::Value* storage = MutableStorage("tokenPagination"); return client::JsonValueToMutableCppValueHelper<TokenPagination >(storage); } } // namespace google_youtube_api <file_sep>/service_apis/youtube/google/youtube_api/live_chat_message_author_details.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_LIVE_CHAT_MESSAGE_AUTHOR_DETAILS_H_ #define GOOGLE_YOUTUBE_API_LIVE_CHAT_MESSAGE_AUTHOR_DETAILS_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * No description provided. * * @ingroup DataObject */ class LiveChatMessageAuthorDetails : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static LiveChatMessageAuthorDetails* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveChatMessageAuthorDetails(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveChatMessageAuthorDetails(Json::Value* storage); /** * Standard destructor. */ virtual ~LiveChatMessageAuthorDetails(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::LiveChatMessageAuthorDetails</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::LiveChatMessageAuthorDetails"); } /** * Determine if the '<code>channelId</code>' attribute was set. * * @return true if the '<code>channelId</code>' attribute was set. */ bool has_channel_id() const { return Storage().isMember("channelId"); } /** * Clears the '<code>channelId</code>' attribute. */ void clear_channel_id() { MutableStorage()->removeMember("channelId"); } /** * Get the value of the '<code>channelId</code>' attribute. */ const StringPiece get_channel_id() const { const Json::Value& v = Storage("channelId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>channelId</code>' attribute. * * The YouTube channel ID. * * @param[in] value The new value. */ void set_channel_id(const StringPiece& value) { *MutableStorage("channelId") = value.data(); } /** * Determine if the '<code>channelUrl</code>' attribute was set. * * @return true if the '<code>channelUrl</code>' attribute was set. */ bool has_channel_url() const { return Storage().isMember("channelUrl"); } /** * Clears the '<code>channelUrl</code>' attribute. */ void clear_channel_url() { MutableStorage()->removeMember("channelUrl"); } /** * Get the value of the '<code>channelUrl</code>' attribute. */ const StringPiece get_channel_url() const { const Json::Value& v = Storage("channelUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>channelUrl</code>' attribute. * * The channel's URL. * * @param[in] value The new value. */ void set_channel_url(const StringPiece& value) { *MutableStorage("channelUrl") = value.data(); } /** * Determine if the '<code>displayName</code>' attribute was set. * * @return true if the '<code>displayName</code>' attribute was set. */ bool has_display_name() const { return Storage().isMember("displayName"); } /** * Clears the '<code>displayName</code>' attribute. */ void clear_display_name() { MutableStorage()->removeMember("displayName"); } /** * Get the value of the '<code>displayName</code>' attribute. */ const StringPiece get_display_name() const { const Json::Value& v = Storage("displayName"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>displayName</code>' attribute. * * The channel's display name. * * @param[in] value The new value. */ void set_display_name(const StringPiece& value) { *MutableStorage("displayName") = value.data(); } /** * Determine if the '<code>isChatModerator</code>' attribute was set. * * @return true if the '<code>isChatModerator</code>' attribute was set. */ bool has_is_chat_moderator() const { return Storage().isMember("isChatModerator"); } /** * Clears the '<code>isChatModerator</code>' attribute. */ void clear_is_chat_moderator() { MutableStorage()->removeMember("isChatModerator"); } /** * Get the value of the '<code>isChatModerator</code>' attribute. */ bool get_is_chat_moderator() const { const Json::Value& storage = Storage("isChatModerator"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>isChatModerator</code>' attribute. * * Whether the author is a moderator of the live chat. * * @param[in] value The new value. */ void set_is_chat_moderator(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("isChatModerator")); } /** * Determine if the '<code>isChatOwner</code>' attribute was set. * * @return true if the '<code>isChatOwner</code>' attribute was set. */ bool has_is_chat_owner() const { return Storage().isMember("isChatOwner"); } /** * Clears the '<code>isChatOwner</code>' attribute. */ void clear_is_chat_owner() { MutableStorage()->removeMember("isChatOwner"); } /** * Get the value of the '<code>isChatOwner</code>' attribute. */ bool get_is_chat_owner() const { const Json::Value& storage = Storage("isChatOwner"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>isChatOwner</code>' attribute. * * Whether the author is the owner of the live chat. * * @param[in] value The new value. */ void set_is_chat_owner(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("isChatOwner")); } /** * Determine if the '<code>isChatSponsor</code>' attribute was set. * * @return true if the '<code>isChatSponsor</code>' attribute was set. */ bool has_is_chat_sponsor() const { return Storage().isMember("isChatSponsor"); } /** * Clears the '<code>isChatSponsor</code>' attribute. */ void clear_is_chat_sponsor() { MutableStorage()->removeMember("isChatSponsor"); } /** * Get the value of the '<code>isChatSponsor</code>' attribute. */ bool get_is_chat_sponsor() const { const Json::Value& storage = Storage("isChatSponsor"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>isChatSponsor</code>' attribute. * * Whether the author is a sponsor of the live chat. * * @param[in] value The new value. */ void set_is_chat_sponsor(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("isChatSponsor")); } /** * Determine if the '<code>isVerified</code>' attribute was set. * * @return true if the '<code>isVerified</code>' attribute was set. */ bool has_is_verified() const { return Storage().isMember("isVerified"); } /** * Clears the '<code>isVerified</code>' attribute. */ void clear_is_verified() { MutableStorage()->removeMember("isVerified"); } /** * Get the value of the '<code>isVerified</code>' attribute. */ bool get_is_verified() const { const Json::Value& storage = Storage("isVerified"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>isVerified</code>' attribute. * * Whether the author's identity has been verified by YouTube. * * @param[in] value The new value. */ void set_is_verified(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("isVerified")); } /** * Determine if the '<code>profileImageUrl</code>' attribute was set. * * @return true if the '<code>profileImageUrl</code>' attribute was set. */ bool has_profile_image_url() const { return Storage().isMember("profileImageUrl"); } /** * Clears the '<code>profileImageUrl</code>' attribute. */ void clear_profile_image_url() { MutableStorage()->removeMember("profileImageUrl"); } /** * Get the value of the '<code>profileImageUrl</code>' attribute. */ const StringPiece get_profile_image_url() const { const Json::Value& v = Storage("profileImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>profileImageUrl</code>' attribute. * * The channels's avatar URL. * * @param[in] value The new value. */ void set_profile_image_url(const StringPiece& value) { *MutableStorage("profileImageUrl") = value.data(); } private: void operator=(const LiveChatMessageAuthorDetails&); }; // LiveChatMessageAuthorDetails } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_LIVE_CHAT_MESSAGE_AUTHOR_DETAILS_H_ <file_sep>/src/samples/abstract_gplus_login_flow.h /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #ifndef GOOGLEAPIS_SAMPLES_ABSTRACT_GPLUS_LOGIN_FLOW_H_ #define GOOGLEAPIS_SAMPLES_ABSTRACT_GPLUS_LOGIN_FLOW_H_ #include <string> using std::string; #include "samples/abstract_login_flow.h" #include "googleapis/client/util/abstract_webserver.h" #include "googleapis/base/macros.h" namespace googleapis { namespace client { class OAuth2Credential; } namespace sample { using client::WebServerRequest; /* * Component for having the browser fetch access tokens using G+ sign-in. * @ingroup Samples */ class AbstractGplusLoginFlow : public AbstractLoginFlow { public: /* * Standard constructor. */ explicit AbstractGplusLoginFlow( const string& cookie_name, const string& redirect_name, client::OAuth2AuthorizationFlow* flow); /* * Standard destructor. */ virtual ~AbstractGplusLoginFlow(); void set_client_id(const string& id) { client_id_ = id; } const string& client_id() const { return client_id_; } void set_scopes(const string& s) { scopes_ = s; } const string& scopes() const { return scopes_; } bool log_to_console() const { return log_to_console_; } void set_log_to_console(bool on) { log_to_console_ = on; } /* * Render HTML javascript stuff that goes in the head block. */ virtual string GetPrerequisiteHeadHtml(); /* * Render the callback javascript HTML block. * * This includes the script tags so can go anywhere. * * @param[in] state The state query parameter value when redirecting. * @param[in] immediate_block Javascript statement to call when * immediate fails (after revoking tokens). * @param[in] success_block Javascript statement to execute on login. * This is usually something like window.location='...'. * Can be empty. * @param[in] failure_block Javascript statement to execute on failure. * The error description is in a javascript variable 'error'. * Can be empty. */ virtual string GetSigninCallbackJavascriptHtml( const string& state, const string& immediate_block, const string& success_block, const string& failure_block); /* * Returns HTML rendering the G+ Sign-in buton. * * @param[in] default_visible If true make the button visible by default. * The button will be made visible if login is needed, * and invisible once logged in. */ virtual string GetSigninButtonHtml(bool default_visible); protected: virtual googleapis::util::Status DoInitiateAuthorizationFlow( WebServerRequest* request, const string& redirect_url); /* * Handles the poke callback when toens are received. * * Updates (or creates) user data for the user this request is on behalf of. * * @param[in] request Contains state, access_token and * query parametersa. Has cooke for our cookie_id. * * @return MHD_YES or MHD_NO for MicroHttpd API */ virtual googleapis::util::Status DoHandleAccessTokenUrl(WebServerRequest* request); private: string client_id_; string scopes_; bool log_to_console_; DISALLOW_COPY_AND_ASSIGN(AbstractGplusLoginFlow); }; } // namespace sample } // namespace googleapis #endif // GOOGLEAPIS_SAMPLES_ABSTRACT_GPLUS_LOGIN_FLOW_H_ <file_sep>/service_apis/youtube/google/youtube_api/geo_point.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_GEO_POINT_H_ #define GOOGLE_YOUTUBE_API_GEO_POINT_H_ #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Geographical coordinates of a point, in WGS84. * * @ingroup DataObject */ class GeoPoint : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static GeoPoint* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit GeoPoint(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit GeoPoint(Json::Value* storage); /** * Standard destructor. */ virtual ~GeoPoint(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::GeoPoint</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::GeoPoint"); } /** * Determine if the '<code>altitude</code>' attribute was set. * * @return true if the '<code>altitude</code>' attribute was set. */ bool has_altitude() const { return Storage().isMember("altitude"); } /** * Clears the '<code>altitude</code>' attribute. */ void clear_altitude() { MutableStorage()->removeMember("altitude"); } /** * Get the value of the '<code>altitude</code>' attribute. */ double get_altitude() const { const Json::Value& storage = Storage("altitude"); return client::JsonValueToCppValueHelper<double >(storage); } /** * Change the '<code>altitude</code>' attribute. * * Altitude above the reference ellipsoid, in meters. * * @param[in] value The new value. */ void set_altitude(double value) { client::SetJsonValueFromCppValueHelper<double >( value, MutableStorage("altitude")); } /** * Determine if the '<code>latitude</code>' attribute was set. * * @return true if the '<code>latitude</code>' attribute was set. */ bool has_latitude() const { return Storage().isMember("latitude"); } /** * Clears the '<code>latitude</code>' attribute. */ void clear_latitude() { MutableStorage()->removeMember("latitude"); } /** * Get the value of the '<code>latitude</code>' attribute. */ double get_latitude() const { const Json::Value& storage = Storage("latitude"); return client::JsonValueToCppValueHelper<double >(storage); } /** * Change the '<code>latitude</code>' attribute. * * Latitude in degrees. * * @param[in] value The new value. */ void set_latitude(double value) { client::SetJsonValueFromCppValueHelper<double >( value, MutableStorage("latitude")); } /** * Determine if the '<code>longitude</code>' attribute was set. * * @return true if the '<code>longitude</code>' attribute was set. */ bool has_longitude() const { return Storage().isMember("longitude"); } /** * Clears the '<code>longitude</code>' attribute. */ void clear_longitude() { MutableStorage()->removeMember("longitude"); } /** * Get the value of the '<code>longitude</code>' attribute. */ double get_longitude() const { const Json::Value& storage = Storage("longitude"); return client::JsonValueToCppValueHelper<double >(storage); } /** * Change the '<code>longitude</code>' attribute. * * Longitude in degrees. * * @param[in] value The new value. */ void set_longitude(double value) { client::SetJsonValueFromCppValueHelper<double >( value, MutableStorage("longitude")); } private: void operator=(const GeoPoint&); }; // GeoPoint } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_GEO_POINT_H_ <file_sep>/service_apis/youtube/CMakeLists.txt # This is a CMake file for YouTube Data API v3 # using the Google APIs Client Library for C++. # # See http://google.github.io/google-api-cpp-client/latest/start/get_started # for more information about what to do with this file. project (youtube) INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/.) add_subdirectory(google/youtube_api) <file_sep>/service_apis/youtube/google/youtube_api/subscription_snippet.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_SUBSCRIPTION_SNIPPET_H_ #define GOOGLE_YOUTUBE_API_SUBSCRIPTION_SNIPPET_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/resource_id.h" #include "google/youtube_api/thumbnail_details.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Basic details about a subscription, including title, description and * thumbnails of the subscribed item. * * @ingroup DataObject */ class SubscriptionSnippet : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static SubscriptionSnippet* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit SubscriptionSnippet(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit SubscriptionSnippet(Json::Value* storage); /** * Standard destructor. */ virtual ~SubscriptionSnippet(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::SubscriptionSnippet</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::SubscriptionSnippet"); } /** * Determine if the '<code>channelId</code>' attribute was set. * * @return true if the '<code>channelId</code>' attribute was set. */ bool has_channel_id() const { return Storage().isMember("channelId"); } /** * Clears the '<code>channelId</code>' attribute. */ void clear_channel_id() { MutableStorage()->removeMember("channelId"); } /** * Get the value of the '<code>channelId</code>' attribute. */ const StringPiece get_channel_id() const { const Json::Value& v = Storage("channelId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>channelId</code>' attribute. * * The ID that YouTube uses to uniquely identify the subscriber's channel. * * @param[in] value The new value. */ void set_channel_id(const StringPiece& value) { *MutableStorage("channelId") = value.data(); } /** * Determine if the '<code>channelTitle</code>' attribute was set. * * @return true if the '<code>channelTitle</code>' attribute was set. */ bool has_channel_title() const { return Storage().isMember("channelTitle"); } /** * Clears the '<code>channelTitle</code>' attribute. */ void clear_channel_title() { MutableStorage()->removeMember("channelTitle"); } /** * Get the value of the '<code>channelTitle</code>' attribute. */ const StringPiece get_channel_title() const { const Json::Value& v = Storage("channelTitle"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>channelTitle</code>' attribute. * * Channel title for the channel that the subscription belongs to. * * @param[in] value The new value. */ void set_channel_title(const StringPiece& value) { *MutableStorage("channelTitle") = value.data(); } /** * Determine if the '<code>description</code>' attribute was set. * * @return true if the '<code>description</code>' attribute was set. */ bool has_description() const { return Storage().isMember("description"); } /** * Clears the '<code>description</code>' attribute. */ void clear_description() { MutableStorage()->removeMember("description"); } /** * Get the value of the '<code>description</code>' attribute. */ const StringPiece get_description() const { const Json::Value& v = Storage("description"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>description</code>' attribute. * * The subscription's details. * * @param[in] value The new value. */ void set_description(const StringPiece& value) { *MutableStorage("description") = value.data(); } /** * Determine if the '<code>publishedAt</code>' attribute was set. * * @return true if the '<code>publishedAt</code>' attribute was set. */ bool has_published_at() const { return Storage().isMember("publishedAt"); } /** * Clears the '<code>publishedAt</code>' attribute. */ void clear_published_at() { MutableStorage()->removeMember("publishedAt"); } /** * Get the value of the '<code>publishedAt</code>' attribute. */ client::DateTime get_published_at() const { const Json::Value& storage = Storage("publishedAt"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>publishedAt</code>' attribute. * * The date and time that the subscription was created. The value is specified * in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. * * @param[in] value The new value. */ void set_published_at(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("publishedAt")); } /** * Determine if the '<code>resourceId</code>' attribute was set. * * @return true if the '<code>resourceId</code>' attribute was set. */ bool has_resource_id() const { return Storage().isMember("resourceId"); } /** * Clears the '<code>resourceId</code>' attribute. */ void clear_resource_id() { MutableStorage()->removeMember("resourceId"); } /** * Get a reference to the value of the '<code>resourceId</code>' attribute. */ const ResourceId get_resource_id() const; /** * Gets a reference to a mutable value of the '<code>resourceId</code>' * property. * * The id object contains information about the channel that the user * subscribed to. * * @return The result can be modified to change the attribute value. */ ResourceId mutable_resourceId(); /** * Determine if the '<code>thumbnails</code>' attribute was set. * * @return true if the '<code>thumbnails</code>' attribute was set. */ bool has_thumbnails() const { return Storage().isMember("thumbnails"); } /** * Clears the '<code>thumbnails</code>' attribute. */ void clear_thumbnails() { MutableStorage()->removeMember("thumbnails"); } /** * Get a reference to the value of the '<code>thumbnails</code>' attribute. */ const ThumbnailDetails get_thumbnails() const; /** * Gets a reference to a mutable value of the '<code>thumbnails</code>' * property. * * A map of thumbnail images associated with the video. For each object in the * map, the key is the name of the thumbnail image, and the value is an object * that contains other information about the thumbnail. * * @return The result can be modified to change the attribute value. */ ThumbnailDetails mutable_thumbnails(); /** * Determine if the '<code>title</code>' attribute was set. * * @return true if the '<code>title</code>' attribute was set. */ bool has_title() const { return Storage().isMember("title"); } /** * Clears the '<code>title</code>' attribute. */ void clear_title() { MutableStorage()->removeMember("title"); } /** * Get the value of the '<code>title</code>' attribute. */ const StringPiece get_title() const { const Json::Value& v = Storage("title"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>title</code>' attribute. * * The subscription's title. * * @param[in] value The new value. */ void set_title(const StringPiece& value) { *MutableStorage("title") = value.data(); } private: void operator=(const SubscriptionSnippet&); }; // SubscriptionSnippet } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_SUBSCRIPTION_SNIPPET_H_ <file_sep>/service_apis/youtube/google/youtube_api/live_chat_poll_item.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_LIVE_CHAT_POLL_ITEM_H_ #define GOOGLE_YOUTUBE_API_LIVE_CHAT_POLL_ITEM_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * No description provided. * * @ingroup DataObject */ class LiveChatPollItem : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static LiveChatPollItem* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveChatPollItem(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveChatPollItem(Json::Value* storage); /** * Standard destructor. */ virtual ~LiveChatPollItem(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::LiveChatPollItem</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::LiveChatPollItem"); } /** * Determine if the '<code>description</code>' attribute was set. * * @return true if the '<code>description</code>' attribute was set. */ bool has_description() const { return Storage().isMember("description"); } /** * Clears the '<code>description</code>' attribute. */ void clear_description() { MutableStorage()->removeMember("description"); } /** * Get the value of the '<code>description</code>' attribute. */ const StringPiece get_description() const { const Json::Value& v = Storage("description"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>description</code>' attribute. * * Plain text description of the item. * * @param[in] value The new value. */ void set_description(const StringPiece& value) { *MutableStorage("description") = value.data(); } /** * Determine if the '<code>itemId</code>' attribute was set. * * @return true if the '<code>itemId</code>' attribute was set. */ bool has_item_id() const { return Storage().isMember("itemId"); } /** * Clears the '<code>itemId</code>' attribute. */ void clear_item_id() { MutableStorage()->removeMember("itemId"); } /** * Get the value of the '<code>itemId</code>' attribute. */ const StringPiece get_item_id() const { const Json::Value& v = Storage("itemId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>itemId</code>' attribute. * @param[in] value The new value. */ void set_item_id(const StringPiece& value) { *MutableStorage("itemId") = value.data(); } private: void operator=(const LiveChatPollItem&); }; // LiveChatPollItem } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_LIVE_CHAT_POLL_ITEM_H_ <file_sep>/README.md # Google API C++ Client For more information regarding installation, consult the following document: http://google.github.io/google-api-cpp-client/latest/start/installation.html To get started using the Google APIs Client Library for C++ see: http://google.github.io/google-api-cpp-client/latest/start/get_started.html The Doxygen-generated API reference is available online at: http://google.github.io/google-api-cpp-client/latest/doxygen/index.html For the current Google APIs Client Library for C++ see: http://github.com/google/google-api-cpp-client/ The current installation has only been tested on Unix/Linux systems and OS/X. This release does not support Windows yet. The following sequence of actions should result in a turnkey build of the client libraries from the source code given only: ## Prerequisites: * python (Available from http://www.python.org/getit/) - verified with versions 2.6.4 and 2.7.3 * C++ compiler and Make - Mac OSX https://developer.apple.com/xcode/ - Linux http://gcc.gnu.org/ * CMake - Either http://www.cmake.org/cmake/resources/software.html - or run ./prepare_dependencies.py cmake and restart your shell to get the updated path. ## Bootstrap Steps: ./prepare_dependencies.py mkdir build && cd build ../external_dependencies/install/bin/cmake .. make calendar_sample To download additional APIs specialized for individual Google Services see: http://google.github.io/google-api-cpp-client/latest/available_service_apis.html and use this precise version of the apis client generator: https://github.com/google/apis-client-generator/tree/6b13208a5d2c3e00161636a86a19cb5cc9b2519b Here's an example invocation: $ python apis-client-generator/src/googleapis/codegen/generate_library.py --api_name=drive --api_version=v2 --language=cpp --output_dir=/tmp/generated It should be possible to build this from existing installed libraries. However, the build scripts are not yet written to find them. For initial support simplicity we download and build all the dependencies in the prepare_dependencies.py script for the time being as a one-time brute force preparation. ### Getting Help If you have problems, questions or suggestions, contact: The Google group at https://groups.google.com/group/google-api-cpp-client Or you may also ask questions on StackOverflow at: http://stackoverflow.com with the tag google-api-cpp-client ## Status This SDK is in maintanance mode. The patches being made are mostly for portability and/or to remove unneeded pieces. We are not set up to accept pull requests at this time, nor will be in the forseable future. Please submit suggestions as issues. ### About the branches The master branch is where development is done. It usually is compatible with the generated libraries available from from google.developers.com. On occasion it gets aheaad of those. It usually catches up in a few days. The latest generated libraries for any Google API is available automatically from https://developers.google.com/resources/api-libraries/download/<API>/<VERSION>/cpp For example, for Drive/v2, you would use https://developers.google.com/resources/api-libraries/download/drive/v2/cpp <file_sep>/service_apis/drive/google/drive_api/drive_api.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 #ifndef GOOGLE_DRIVE_API_DRIVE_API_H_ #define GOOGLE_DRIVE_API_DRIVE_API_H_ #include "google/drive_api/user.h" #include "google/drive_api/about.h" #include "google/drive_api/app.h" #include "google/drive_api/app_list.h" #include "google/drive_api/parent_reference.h" #include "google/drive_api/permission.h" #include "google/drive_api/property.h" #include "google/drive_api/file.h" #include "google/drive_api/team_drive.h" #include "google/drive_api/change.h" #include "google/drive_api/change_list.h" #include "google/drive_api/channel.h" #include "google/drive_api/child_reference.h" #include "google/drive_api/child_list.h" #include "google/drive_api/comment_reply.h" #include "google/drive_api/comment.h" #include "google/drive_api/comment_list.h" #include "google/drive_api/comment_reply_list.h" #include "google/drive_api/file_list.h" #include "google/drive_api/generated_ids.h" #include "google/drive_api/parent_list.h" #include "google/drive_api/permission_id.h" #include "google/drive_api/permission_list.h" #include "google/drive_api/property_list.h" #include "google/drive_api/revision.h" #include "google/drive_api/revision_list.h" #include "google/drive_api/start_page_token.h" #include "google/drive_api/team_drive_list.h" #include "google/drive_api/drive_service.h" #endif // GOOGLE_DRIVE_API_DRIVE_API_H_ <file_sep>/service_apis/youtube/google/youtube_api/activity_content_details.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_ACTIVITY_CONTENT_DETAILS_H_ #define GOOGLE_YOUTUBE_API_ACTIVITY_CONTENT_DETAILS_H_ #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/activity_content_details_bulletin.h" #include "google/youtube_api/activity_content_details_channel_item.h" #include "google/youtube_api/activity_content_details_comment.h" #include "google/youtube_api/activity_content_details_favorite.h" #include "google/youtube_api/activity_content_details_like.h" #include "google/youtube_api/activity_content_details_playlist_item.h" #include "google/youtube_api/activity_content_details_promoted_item.h" #include "google/youtube_api/activity_content_details_recommendation.h" #include "google/youtube_api/activity_content_details_social.h" #include "google/youtube_api/activity_content_details_subscription.h" #include "google/youtube_api/activity_content_details_upload.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Details about the content of an activity: the video that was shared, the * channel that was subscribed to, etc. * * @ingroup DataObject */ class ActivityContentDetails : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static ActivityContentDetails* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ActivityContentDetails(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ActivityContentDetails(Json::Value* storage); /** * Standard destructor. */ virtual ~ActivityContentDetails(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::ActivityContentDetails</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::ActivityContentDetails"); } /** * Determine if the '<code>bulletin</code>' attribute was set. * * @return true if the '<code>bulletin</code>' attribute was set. */ bool has_bulletin() const { return Storage().isMember("bulletin"); } /** * Clears the '<code>bulletin</code>' attribute. */ void clear_bulletin() { MutableStorage()->removeMember("bulletin"); } /** * Get a reference to the value of the '<code>bulletin</code>' attribute. */ const ActivityContentDetailsBulletin get_bulletin() const; /** * Gets a reference to a mutable value of the '<code>bulletin</code>' * property. * * The bulletin object contains details about a channel bulletin post. This * object is only present if the snippet.type is bulletin. * * @return The result can be modified to change the attribute value. */ ActivityContentDetailsBulletin mutable_bulletin(); /** * Determine if the '<code>channelItem</code>' attribute was set. * * @return true if the '<code>channelItem</code>' attribute was set. */ bool has_channel_item() const { return Storage().isMember("channelItem"); } /** * Clears the '<code>channelItem</code>' attribute. */ void clear_channel_item() { MutableStorage()->removeMember("channelItem"); } /** * Get a reference to the value of the '<code>channelItem</code>' attribute. */ const ActivityContentDetailsChannelItem get_channel_item() const; /** * Gets a reference to a mutable value of the '<code>channelItem</code>' * property. * * The channelItem object contains details about a resource which was added to * a channel. This property is only present if the snippet.type is * channelItem. * * @return The result can be modified to change the attribute value. */ ActivityContentDetailsChannelItem mutable_channelItem(); /** * Determine if the '<code>comment</code>' attribute was set. * * @return true if the '<code>comment</code>' attribute was set. */ bool has_comment() const { return Storage().isMember("comment"); } /** * Clears the '<code>comment</code>' attribute. */ void clear_comment() { MutableStorage()->removeMember("comment"); } /** * Get a reference to the value of the '<code>comment</code>' attribute. */ const ActivityContentDetailsComment get_comment() const; /** * Gets a reference to a mutable value of the '<code>comment</code>' property. * * The comment object contains information about a resource that received a * comment. This property is only present if the snippet.type is comment. * * @return The result can be modified to change the attribute value. */ ActivityContentDetailsComment mutable_comment(); /** * Determine if the '<code>favorite</code>' attribute was set. * * @return true if the '<code>favorite</code>' attribute was set. */ bool has_favorite() const { return Storage().isMember("favorite"); } /** * Clears the '<code>favorite</code>' attribute. */ void clear_favorite() { MutableStorage()->removeMember("favorite"); } /** * Get a reference to the value of the '<code>favorite</code>' attribute. */ const ActivityContentDetailsFavorite get_favorite() const; /** * Gets a reference to a mutable value of the '<code>favorite</code>' * property. * * The favorite object contains information about a video that was marked as a * favorite video. This property is only present if the snippet.type is * favorite. * * @return The result can be modified to change the attribute value. */ ActivityContentDetailsFavorite mutable_favorite(); /** * Determine if the '<code>like</code>' attribute was set. * * @return true if the '<code>like</code>' attribute was set. */ bool has_like() const { return Storage().isMember("like"); } /** * Clears the '<code>like</code>' attribute. */ void clear_like() { MutableStorage()->removeMember("like"); } /** * Get a reference to the value of the '<code>like</code>' attribute. */ const ActivityContentDetailsLike get_like() const; /** * Gets a reference to a mutable value of the '<code>like</code>' property. * * The like object contains information about a resource that received a * positive (like) rating. This property is only present if the snippet.type * is like. * * @return The result can be modified to change the attribute value. */ ActivityContentDetailsLike mutable_like(); /** * Determine if the '<code>playlistItem</code>' attribute was set. * * @return true if the '<code>playlistItem</code>' attribute was set. */ bool has_playlist_item() const { return Storage().isMember("playlistItem"); } /** * Clears the '<code>playlistItem</code>' attribute. */ void clear_playlist_item() { MutableStorage()->removeMember("playlistItem"); } /** * Get a reference to the value of the '<code>playlistItem</code>' attribute. */ const ActivityContentDetailsPlaylistItem get_playlist_item() const; /** * Gets a reference to a mutable value of the '<code>playlistItem</code>' * property. * * The playlistItem object contains information about a new playlist item. * This property is only present if the snippet.type is playlistItem. * * @return The result can be modified to change the attribute value. */ ActivityContentDetailsPlaylistItem mutable_playlistItem(); /** * Determine if the '<code>promotedItem</code>' attribute was set. * * @return true if the '<code>promotedItem</code>' attribute was set. */ bool has_promoted_item() const { return Storage().isMember("promotedItem"); } /** * Clears the '<code>promotedItem</code>' attribute. */ void clear_promoted_item() { MutableStorage()->removeMember("promotedItem"); } /** * Get a reference to the value of the '<code>promotedItem</code>' attribute. */ const ActivityContentDetailsPromotedItem get_promoted_item() const; /** * Gets a reference to a mutable value of the '<code>promotedItem</code>' * property. * * The promotedItem object contains details about a resource which is being * promoted. This property is only present if the snippet.type is * promotedItem. * * @return The result can be modified to change the attribute value. */ ActivityContentDetailsPromotedItem mutable_promotedItem(); /** * Determine if the '<code>recommendation</code>' attribute was set. * * @return true if the '<code>recommendation</code>' attribute was set. */ bool has_recommendation() const { return Storage().isMember("recommendation"); } /** * Clears the '<code>recommendation</code>' attribute. */ void clear_recommendation() { MutableStorage()->removeMember("recommendation"); } /** * Get a reference to the value of the '<code>recommendation</code>' * attribute. */ const ActivityContentDetailsRecommendation get_recommendation() const; /** * Gets a reference to a mutable value of the '<code>recommendation</code>' * property. * * The recommendation object contains information about a recommended * resource. This property is only present if the snippet.type is * recommendation. * * @return The result can be modified to change the attribute value. */ ActivityContentDetailsRecommendation mutable_recommendation(); /** * Determine if the '<code>social</code>' attribute was set. * * @return true if the '<code>social</code>' attribute was set. */ bool has_social() const { return Storage().isMember("social"); } /** * Clears the '<code>social</code>' attribute. */ void clear_social() { MutableStorage()->removeMember("social"); } /** * Get a reference to the value of the '<code>social</code>' attribute. */ const ActivityContentDetailsSocial get_social() const; /** * Gets a reference to a mutable value of the '<code>social</code>' property. * * The social object contains details about a social network post. This * property is only present if the snippet.type is social. * * @return The result can be modified to change the attribute value. */ ActivityContentDetailsSocial mutable_social(); /** * Determine if the '<code>subscription</code>' attribute was set. * * @return true if the '<code>subscription</code>' attribute was set. */ bool has_subscription() const { return Storage().isMember("subscription"); } /** * Clears the '<code>subscription</code>' attribute. */ void clear_subscription() { MutableStorage()->removeMember("subscription"); } /** * Get a reference to the value of the '<code>subscription</code>' attribute. */ const ActivityContentDetailsSubscription get_subscription() const; /** * Gets a reference to a mutable value of the '<code>subscription</code>' * property. * * The subscription object contains information about a channel that a user * subscribed to. This property is only present if the snippet.type is * subscription. * * @return The result can be modified to change the attribute value. */ ActivityContentDetailsSubscription mutable_subscription(); /** * Determine if the '<code>upload</code>' attribute was set. * * @return true if the '<code>upload</code>' attribute was set. */ bool has_upload() const { return Storage().isMember("upload"); } /** * Clears the '<code>upload</code>' attribute. */ void clear_upload() { MutableStorage()->removeMember("upload"); } /** * Get a reference to the value of the '<code>upload</code>' attribute. */ const ActivityContentDetailsUpload get_upload() const; /** * Gets a reference to a mutable value of the '<code>upload</code>' property. * * The upload object contains information about the uploaded video. This * property is only present if the snippet.type is upload. * * @return The result can be modified to change the attribute value. */ ActivityContentDetailsUpload mutable_upload(); private: void operator=(const ActivityContentDetails&); }; // ActivityContentDetails } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_ACTIVITY_CONTENT_DETAILS_H_ <file_sep>/src/samples/command_processor.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <algorithm> #include <iostream> using std::cout; using std::endl; using std::ostream; // NOLINT #include <string> using std::string; #include <map> #include <vector> #include "googleapis/client/data/data_reader.h" #include "googleapis/client/transport/http_response.h" #include "samples/command_processor.h" #include <glog/logging.h> #include "googleapis/strings/ascii_ctype.h" namespace googleapis { using std::cin; using std::cerr; using std::cout; using client::HttpResponse; namespace sample { CommandProcessor::CommandProcessor() : prompt_("> "), log_success_bodies_(false) { } CommandProcessor::~CommandProcessor() { for (CommandEntryMap::const_iterator it = commands_.begin(); it != commands_.end(); ++it) { delete it->second; } } void CommandProcessor::InitCommands() { AddBuiltinCommands(); } void CommandProcessor::AddBuiltinCommands() { AddCommand("quit", new CommandEntry( "", "Quit the program.", NewPermanentCallback(this, &CommandProcessor::QuitHandler))); AddCommand("help", new CommandEntry( "", "Show help.", NewPermanentCallback(this, &CommandProcessor::HelpHandler))); AddCommand("quiet", new CommandEntry( "", "Dont show successful response bodies.", NewPermanentCallback(this, &CommandProcessor::VerboseHandler, 0))); AddCommand("verbose", new CommandEntry( "", "Show successful response bodies.", NewPermanentCallback(this, &CommandProcessor::VerboseHandler, 1))); } void CommandProcessor::AddCommand(string name, CommandEntry* details) { commands_.insert(std::make_pair(name, details)); } bool CommandProcessor::CheckAndLogResponse(HttpResponse* response) { googleapis::util::Status transport_status = response->transport_status(); // Rewind the stream before we dump it since this could get called after // ExecuteAndParseResponse which will have read the result. response->body_reader()->SetOffset(0); bool response_was_ok; if (!transport_status.ok()) { cerr << "ERROR: " << transport_status.error_message() << std::endl; return false; } else if (!response->ok()) { string body; googleapis::util::Status status = response->GetBodyString(&body); if (!status.ok()) { body.append("ERROR reading HTTP response body: "); body.append(status.error_message()); } cerr << "ERROR(" << response->http_code() << "): " << body << std::endl; response_was_ok = false; } else { cout << "OK(" << response->http_code() << ")" << std::endl; if (log_success_bodies_) { string body; googleapis::util::Status status = response->GetBodyString(&body); if (!status.ok()) { body.append("ERROR reading HTTP response body: "); body.append(status.error_message()); } cout << "---------- [begin response body] ----------" << std::endl; cout << body << std::endl; cout << "----------- [end response body] -----------" << std::endl; } response_was_ok = true; } // Restore offset in case someone downstream wants to read the body again. if (response->body_reader()->SetOffset(0) != 0) { LOG(WARNING) << "Could not reset body offset so future reads (if any) will fail."; } return response_was_ok; } void CommandProcessor::VerboseHandler( int level, const string&, const std::vector<string>&) { if (level == 0) { cout << "Being quiet." << std::endl; log_success_bodies_ = false; } else { cout << "Being verbose." << std::endl; log_success_bodies_ = true; } } void CommandProcessor::QuitHandler(const string&, const std::vector<string>&) { VLOG(1) << "Got QUIT"; done_ = true; } void CommandProcessor::HelpHandler(const string&, const std::vector<string>&) { std::vector<std::pair<string, const CommandEntry*> > all; for (CommandEntryMap::const_iterator it = commands_.begin(); it != commands_.end(); ++it) { all.push_back(*it); } std::sort(all.begin(), all.end(), &CommandEntry::CompareEntry); string help = "Commands:\n"; for (auto it = all.begin(); it != all.end(); ++it) { help.append(it->first); if (!it->second->args.empty()) { help.append(" "); help.append(it->second->args); } help.append("\n "); help.append(it->second->help); help.append("\n "); } cout << help << std::endl; } void CommandProcessor::RunShell() { if (!commands_.size()) { // Not called already, such as in a previous invocation to RunShell. InitCommands(); } done_ = false; while (!done_) { cout << std::endl << prompt_; string input; std::getline(cin, input); std::vector<string> args; SplitArgs(input, &args); if (args.size() == 0) continue; string cmd = args[0]; if (commands_.find(cmd) != commands_.end()) { args.erase(args.begin()); // remove command commands_[cmd]->runner->Run(cmd, args); } else { cerr << "Error: Unknown command '" << cmd << "' (try 'help')\n"; } } } // static bool CommandProcessor::SplitArgs(const string& args, std::vector<string>* list) { bool ok = true; string current; const char* end = args.data() + args.size(); for (const char* pc = args.data(); pc < end; ++pc) { if (ascii_isspace(*pc)) { if (current.empty()) continue; // skip spaces between tokens list->push_back(current); current.clear(); continue; } else if (*pc == '"') { // end current word and start a new one. if (!current.empty()) { list->push_back(current); current.clear(); } // keep the contents inside double quotes but respect escapes. // If there was no close quote, treat it a bad parse. for (++pc; pc < end && *pc != '"'; ++pc) { if (*pc == '\\') { ++pc; if (pc == end) { ok = false; continue; } } current.push_back(*pc); } list->push_back(current); current.clear(); ok = pc < end; continue; } if (*pc == '\\') { ++pc; if (pc == end) { ok = false; continue; } } current.push_back(*pc); } if (!current.empty()) { list->push_back(current); } return ok; } } // namespace sample } // namespace googleapis <file_sep>/service_apis/youtube/google/youtube_api/video.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_VIDEO_H_ #define GOOGLE_YOUTUBE_API_VIDEO_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/video_age_gating.h" #include "google/youtube_api/video_content_details.h" #include "google/youtube_api/video_file_details.h" #include "google/youtube_api/video_live_streaming_details.h" #include "google/youtube_api/video_localization.h" #include "google/youtube_api/video_monetization_details.h" #include "google/youtube_api/video_player.h" #include "google/youtube_api/video_processing_details.h" #include "google/youtube_api/video_project_details.h" #include "google/youtube_api/video_recording_details.h" #include "google/youtube_api/video_snippet.h" #include "google/youtube_api/video_statistics.h" #include "google/youtube_api/video_status.h" #include "google/youtube_api/video_suggestions.h" #include "google/youtube_api/video_topic_details.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * A video resource represents a YouTube video. * * @ingroup DataObject */ class Video : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static Video* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Video(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Video(Json::Value* storage); /** * Standard destructor. */ virtual ~Video(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::Video</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::Video"); } /** * Determine if the '<code>ageGating</code>' attribute was set. * * @return true if the '<code>ageGating</code>' attribute was set. */ bool has_age_gating() const { return Storage().isMember("ageGating"); } /** * Clears the '<code>ageGating</code>' attribute. */ void clear_age_gating() { MutableStorage()->removeMember("ageGating"); } /** * Get a reference to the value of the '<code>ageGating</code>' attribute. */ const VideoAgeGating get_age_gating() const; /** * Gets a reference to a mutable value of the '<code>ageGating</code>' * property. * * Age restriction details related to a video. This data can only be retrieved * by the video owner. * * @return The result can be modified to change the attribute value. */ VideoAgeGating mutable_ageGating(); /** * Determine if the '<code>contentDetails</code>' attribute was set. * * @return true if the '<code>contentDetails</code>' attribute was set. */ bool has_content_details() const { return Storage().isMember("contentDetails"); } /** * Clears the '<code>contentDetails</code>' attribute. */ void clear_content_details() { MutableStorage()->removeMember("contentDetails"); } /** * Get a reference to the value of the '<code>contentDetails</code>' * attribute. */ const VideoContentDetails get_content_details() const; /** * Gets a reference to a mutable value of the '<code>contentDetails</code>' * property. * * The contentDetails object contains information about the video content, * including the length of the video and its aspect ratio. * * @return The result can be modified to change the attribute value. */ VideoContentDetails mutable_contentDetails(); /** * Determine if the '<code>etag</code>' attribute was set. * * @return true if the '<code>etag</code>' attribute was set. */ bool has_etag() const { return Storage().isMember("etag"); } /** * Clears the '<code>etag</code>' attribute. */ void clear_etag() { MutableStorage()->removeMember("etag"); } /** * Get the value of the '<code>etag</code>' attribute. */ const StringPiece get_etag() const { const Json::Value& v = Storage("etag"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>etag</code>' attribute. * * Etag of this resource. * * @param[in] value The new value. */ void set_etag(const StringPiece& value) { *MutableStorage("etag") = value.data(); } /** * Determine if the '<code>fileDetails</code>' attribute was set. * * @return true if the '<code>fileDetails</code>' attribute was set. */ bool has_file_details() const { return Storage().isMember("fileDetails"); } /** * Clears the '<code>fileDetails</code>' attribute. */ void clear_file_details() { MutableStorage()->removeMember("fileDetails"); } /** * Get a reference to the value of the '<code>fileDetails</code>' attribute. */ const VideoFileDetails get_file_details() const; /** * Gets a reference to a mutable value of the '<code>fileDetails</code>' * property. * * The fileDetails object encapsulates information about the video file that * was uploaded to YouTube, including the file's resolution, duration, audio * and video codecs, stream bitrates, and more. This data can only be * retrieved by the video owner. * * @return The result can be modified to change the attribute value. */ VideoFileDetails mutable_fileDetails(); /** * Determine if the '<code>id</code>' attribute was set. * * @return true if the '<code>id</code>' attribute was set. */ bool has_id() const { return Storage().isMember("id"); } /** * Clears the '<code>id</code>' attribute. */ void clear_id() { MutableStorage()->removeMember("id"); } /** * Get the value of the '<code>id</code>' attribute. */ const StringPiece get_id() const { const Json::Value& v = Storage("id"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>id</code>' attribute. * * The ID that YouTube uses to uniquely identify the video. * * @param[in] value The new value. */ void set_id(const StringPiece& value) { *MutableStorage("id") = value.data(); } /** * Determine if the '<code>kind</code>' attribute was set. * * @return true if the '<code>kind</code>' attribute was set. */ bool has_kind() const { return Storage().isMember("kind"); } /** * Clears the '<code>kind</code>' attribute. */ void clear_kind() { MutableStorage()->removeMember("kind"); } /** * Get the value of the '<code>kind</code>' attribute. */ const StringPiece get_kind() const { const Json::Value& v = Storage("kind"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kind</code>' attribute. * * Identifies what kind of resource this is. Value: the fixed string * "youtube#video". * * @param[in] value The new value. */ void set_kind(const StringPiece& value) { *MutableStorage("kind") = value.data(); } /** * Determine if the '<code>liveStreamingDetails</code>' attribute was set. * * @return true if the '<code>liveStreamingDetails</code>' attribute was set. */ bool has_live_streaming_details() const { return Storage().isMember("liveStreamingDetails"); } /** * Clears the '<code>liveStreamingDetails</code>' attribute. */ void clear_live_streaming_details() { MutableStorage()->removeMember("liveStreamingDetails"); } /** * Get a reference to the value of the '<code>liveStreamingDetails</code>' * attribute. */ const VideoLiveStreamingDetails get_live_streaming_details() const; /** * Gets a reference to a mutable value of the * '<code>liveStreamingDetails</code>' property. * * The liveStreamingDetails object contains metadata about a live video * broadcast. The object will only be present in a video resource if the video * is an upcoming, live, or completed live broadcast. * * @return The result can be modified to change the attribute value. */ VideoLiveStreamingDetails mutable_liveStreamingDetails(); /** * Determine if the '<code>localizations</code>' attribute was set. * * @return true if the '<code>localizations</code>' attribute was set. */ bool has_localizations() const { return Storage().isMember("localizations"); } /** * Clears the '<code>localizations</code>' attribute. */ void clear_localizations() { MutableStorage()->removeMember("localizations"); } /** * Get a reference to the value of the '<code>localizations</code>' attribute. */ const client::JsonCppAssociativeArray<VideoLocalization > get_localizations() const; /** * Gets a reference to a mutable value of the '<code>localizations</code>' * property. * * List with all localizations. * * @return The result can be modified to change the attribute value. */ client::JsonCppAssociativeArray<VideoLocalization > mutable_localizations(); /** * Determine if the '<code>monetizationDetails</code>' attribute was set. * * @return true if the '<code>monetizationDetails</code>' attribute was set. */ bool has_monetization_details() const { return Storage().isMember("monetizationDetails"); } /** * Clears the '<code>monetizationDetails</code>' attribute. */ void clear_monetization_details() { MutableStorage()->removeMember("monetizationDetails"); } /** * Get a reference to the value of the '<code>monetizationDetails</code>' * attribute. */ const VideoMonetizationDetails get_monetization_details() const; /** * Gets a reference to a mutable value of the * '<code>monetizationDetails</code>' property. * * The monetizationDetails object encapsulates information about the * monetization status of the video. * * @return The result can be modified to change the attribute value. */ VideoMonetizationDetails mutable_monetizationDetails(); /** * Determine if the '<code>player</code>' attribute was set. * * @return true if the '<code>player</code>' attribute was set. */ bool has_player() const { return Storage().isMember("player"); } /** * Clears the '<code>player</code>' attribute. */ void clear_player() { MutableStorage()->removeMember("player"); } /** * Get a reference to the value of the '<code>player</code>' attribute. */ const VideoPlayer get_player() const; /** * Gets a reference to a mutable value of the '<code>player</code>' property. * * The player object contains information that you would use to play the video * in an embedded player. * * @return The result can be modified to change the attribute value. */ VideoPlayer mutable_player(); /** * Determine if the '<code>processingDetails</code>' attribute was set. * * @return true if the '<code>processingDetails</code>' attribute was set. */ bool has_processing_details() const { return Storage().isMember("processingDetails"); } /** * Clears the '<code>processingDetails</code>' attribute. */ void clear_processing_details() { MutableStorage()->removeMember("processingDetails"); } /** * Get a reference to the value of the '<code>processingDetails</code>' * attribute. */ const VideoProcessingDetails get_processing_details() const; /** * Gets a reference to a mutable value of the '<code>processingDetails</code>' * property. * * The processingProgress object encapsulates information about YouTube's * progress in processing the uploaded video file. The properties in the * object identify the current processing status and an estimate of the time * remaining until YouTube finishes processing the video. This part also * indicates whether different types of data or content, such as file details * or thumbnail images, are available for the video. * * The processingProgress object is designed to be polled so that the video * uploaded can track the progress that YouTube has made in processing the * uploaded video file. This data can only be retrieved by the video owner. * * @return The result can be modified to change the attribute value. */ VideoProcessingDetails mutable_processingDetails(); /** * Determine if the '<code>projectDetails</code>' attribute was set. * * @return true if the '<code>projectDetails</code>' attribute was set. */ bool has_project_details() const { return Storage().isMember("projectDetails"); } /** * Clears the '<code>projectDetails</code>' attribute. */ void clear_project_details() { MutableStorage()->removeMember("projectDetails"); } /** * Get a reference to the value of the '<code>projectDetails</code>' * attribute. */ const VideoProjectDetails get_project_details() const; /** * Gets a reference to a mutable value of the '<code>projectDetails</code>' * property. * * The projectDetails object contains information about the project specific * video metadata. * * @return The result can be modified to change the attribute value. */ VideoProjectDetails mutable_projectDetails(); /** * Determine if the '<code>recordingDetails</code>' attribute was set. * * @return true if the '<code>recordingDetails</code>' attribute was set. */ bool has_recording_details() const { return Storage().isMember("recordingDetails"); } /** * Clears the '<code>recordingDetails</code>' attribute. */ void clear_recording_details() { MutableStorage()->removeMember("recordingDetails"); } /** * Get a reference to the value of the '<code>recordingDetails</code>' * attribute. */ const VideoRecordingDetails get_recording_details() const; /** * Gets a reference to a mutable value of the '<code>recordingDetails</code>' * property. * * The recordingDetails object encapsulates information about the location, * date and address where the video was recorded. * * @return The result can be modified to change the attribute value. */ VideoRecordingDetails mutable_recordingDetails(); /** * Determine if the '<code>snippet</code>' attribute was set. * * @return true if the '<code>snippet</code>' attribute was set. */ bool has_snippet() const { return Storage().isMember("snippet"); } /** * Clears the '<code>snippet</code>' attribute. */ void clear_snippet() { MutableStorage()->removeMember("snippet"); } /** * Get a reference to the value of the '<code>snippet</code>' attribute. */ const VideoSnippet get_snippet() const; /** * Gets a reference to a mutable value of the '<code>snippet</code>' property. * * The snippet object contains basic details about the video, such as its * title, description, and category. * * @return The result can be modified to change the attribute value. */ VideoSnippet mutable_snippet(); /** * Determine if the '<code>statistics</code>' attribute was set. * * @return true if the '<code>statistics</code>' attribute was set. */ bool has_statistics() const { return Storage().isMember("statistics"); } /** * Clears the '<code>statistics</code>' attribute. */ void clear_statistics() { MutableStorage()->removeMember("statistics"); } /** * Get a reference to the value of the '<code>statistics</code>' attribute. */ const VideoStatistics get_statistics() const; /** * Gets a reference to a mutable value of the '<code>statistics</code>' * property. * * The statistics object contains statistics about the video. * * @return The result can be modified to change the attribute value. */ VideoStatistics mutable_statistics(); /** * Determine if the '<code>status</code>' attribute was set. * * @return true if the '<code>status</code>' attribute was set. */ bool has_status() const { return Storage().isMember("status"); } /** * Clears the '<code>status</code>' attribute. */ void clear_status() { MutableStorage()->removeMember("status"); } /** * Get a reference to the value of the '<code>status</code>' attribute. */ const VideoStatus get_status() const; /** * Gets a reference to a mutable value of the '<code>status</code>' property. * * The status object contains information about the video's uploading, * processing, and privacy statuses. * * @return The result can be modified to change the attribute value. */ VideoStatus mutable_status(); /** * Determine if the '<code>suggestions</code>' attribute was set. * * @return true if the '<code>suggestions</code>' attribute was set. */ bool has_suggestions() const { return Storage().isMember("suggestions"); } /** * Clears the '<code>suggestions</code>' attribute. */ void clear_suggestions() { MutableStorage()->removeMember("suggestions"); } /** * Get a reference to the value of the '<code>suggestions</code>' attribute. */ const VideoSuggestions get_suggestions() const; /** * Gets a reference to a mutable value of the '<code>suggestions</code>' * property. * * The suggestions object encapsulates suggestions that identify opportunities * to improve the video quality or the metadata for the uploaded video. This * data can only be retrieved by the video owner. * * @return The result can be modified to change the attribute value. */ VideoSuggestions mutable_suggestions(); /** * Determine if the '<code>topicDetails</code>' attribute was set. * * @return true if the '<code>topicDetails</code>' attribute was set. */ bool has_topic_details() const { return Storage().isMember("topicDetails"); } /** * Clears the '<code>topicDetails</code>' attribute. */ void clear_topic_details() { MutableStorage()->removeMember("topicDetails"); } /** * Get a reference to the value of the '<code>topicDetails</code>' attribute. */ const VideoTopicDetails get_topic_details() const; /** * Gets a reference to a mutable value of the '<code>topicDetails</code>' * property. * * The topicDetails object encapsulates information about Freebase topics * associated with the video. * * @return The result can be modified to change the attribute value. */ VideoTopicDetails mutable_topicDetails(); private: void operator=(const Video&); }; // Video } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_VIDEO_H_ <file_sep>/service_apis/youtube/google/youtube_api/channel_branding_settings.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Description: // Supports core YouTube features, such as uploading videos, creating and managing playlists, searching for content, and much more. // Classes: // ChannelBrandingSettings // Documentation: // https://developers.google.com/youtube/v3 #include "google/youtube_api/channel_branding_settings.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/channel_settings.h" #include "google/youtube_api/image_settings.h" #include "google/youtube_api/property_value.h" #include "google/youtube_api/watch_settings.h" #include <string> #include "googleapis/strings/strcat.h" namespace google_youtube_api { using namespace googleapis; // Object factory method (static). ChannelBrandingSettings* ChannelBrandingSettings::New() { return new client::JsonCppCapsule<ChannelBrandingSettings>; } // Standard immutable constructor. ChannelBrandingSettings::ChannelBrandingSettings(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. ChannelBrandingSettings::ChannelBrandingSettings(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. ChannelBrandingSettings::~ChannelBrandingSettings() { } // Properties. const ChannelSettings ChannelBrandingSettings::get_channel() const { const Json::Value& storage = Storage("channel"); return client::JsonValueToCppValueHelper<ChannelSettings >(storage); } ChannelSettings ChannelBrandingSettings::mutable_channel() { Json::Value* storage = MutableStorage("channel"); return client::JsonValueToMutableCppValueHelper<ChannelSettings >(storage); } const client::JsonCppArray<PropertyValue > ChannelBrandingSettings::get_hints() const { const Json::Value& storage = Storage("hints"); return client::JsonValueToCppValueHelper<client::JsonCppArray<PropertyValue > >(storage); } client::JsonCppArray<PropertyValue > ChannelBrandingSettings::mutable_hints() { Json::Value* storage = MutableStorage("hints"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<PropertyValue > >(storage); } const ImageSettings ChannelBrandingSettings::get_image() const { const Json::Value& storage = Storage("image"); return client::JsonValueToCppValueHelper<ImageSettings >(storage); } ImageSettings ChannelBrandingSettings::mutable_image() { Json::Value* storage = MutableStorage("image"); return client::JsonValueToMutableCppValueHelper<ImageSettings >(storage); } const WatchSettings ChannelBrandingSettings::get_watch() const { const Json::Value& storage = Storage("watch"); return client::JsonValueToCppValueHelper<WatchSettings >(storage); } WatchSettings ChannelBrandingSettings::mutable_watch() { Json::Value* storage = MutableStorage("watch"); return client::JsonValueToMutableCppValueHelper<WatchSettings >(storage); } } // namespace google_youtube_api <file_sep>/service_apis/youtube/google/youtube_api/video_statistics.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_VIDEO_STATISTICS_H_ #define GOOGLE_YOUTUBE_API_VIDEO_STATISTICS_H_ #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Statistics about the video, such as the number of times the video was viewed * or liked. * * @ingroup DataObject */ class VideoStatistics : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static VideoStatistics* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoStatistics(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoStatistics(Json::Value* storage); /** * Standard destructor. */ virtual ~VideoStatistics(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::VideoStatistics</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::VideoStatistics"); } /** * Determine if the '<code>commentCount</code>' attribute was set. * * @return true if the '<code>commentCount</code>' attribute was set. */ bool has_comment_count() const { return Storage().isMember("commentCount"); } /** * Clears the '<code>commentCount</code>' attribute. */ void clear_comment_count() { MutableStorage()->removeMember("commentCount"); } /** * Get the value of the '<code>commentCount</code>' attribute. */ uint64 get_comment_count() const { const Json::Value& storage = Storage("commentCount"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>commentCount</code>' attribute. * * The number of comments for the video. * * @param[in] value The new value. */ void set_comment_count(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("commentCount")); } /** * Determine if the '<code>dislikeCount</code>' attribute was set. * * @return true if the '<code>dislikeCount</code>' attribute was set. */ bool has_dislike_count() const { return Storage().isMember("dislikeCount"); } /** * Clears the '<code>dislikeCount</code>' attribute. */ void clear_dislike_count() { MutableStorage()->removeMember("dislikeCount"); } /** * Get the value of the '<code>dislikeCount</code>' attribute. */ uint64 get_dislike_count() const { const Json::Value& storage = Storage("dislikeCount"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>dislikeCount</code>' attribute. * * The number of users who have indicated that they disliked the video by * giving it a negative rating. * * @param[in] value The new value. */ void set_dislike_count(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("dislikeCount")); } /** * Determine if the '<code>favoriteCount</code>' attribute was set. * * @return true if the '<code>favoriteCount</code>' attribute was set. */ bool has_favorite_count() const { return Storage().isMember("favoriteCount"); } /** * Clears the '<code>favoriteCount</code>' attribute. */ void clear_favorite_count() { MutableStorage()->removeMember("favoriteCount"); } /** * Get the value of the '<code>favoriteCount</code>' attribute. */ uint64 get_favorite_count() const { const Json::Value& storage = Storage("favoriteCount"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>favoriteCount</code>' attribute. * * The number of users who currently have the video marked as a favorite * video. * * @param[in] value The new value. */ void set_favorite_count(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("favoriteCount")); } /** * Determine if the '<code>likeCount</code>' attribute was set. * * @return true if the '<code>likeCount</code>' attribute was set. */ bool has_like_count() const { return Storage().isMember("likeCount"); } /** * Clears the '<code>likeCount</code>' attribute. */ void clear_like_count() { MutableStorage()->removeMember("likeCount"); } /** * Get the value of the '<code>likeCount</code>' attribute. */ uint64 get_like_count() const { const Json::Value& storage = Storage("likeCount"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>likeCount</code>' attribute. * * The number of users who have indicated that they liked the video by giving * it a positive rating. * * @param[in] value The new value. */ void set_like_count(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("likeCount")); } /** * Determine if the '<code>viewCount</code>' attribute was set. * * @return true if the '<code>viewCount</code>' attribute was set. */ bool has_view_count() const { return Storage().isMember("viewCount"); } /** * Clears the '<code>viewCount</code>' attribute. */ void clear_view_count() { MutableStorage()->removeMember("viewCount"); } /** * Get the value of the '<code>viewCount</code>' attribute. */ uint64 get_view_count() const { const Json::Value& storage = Storage("viewCount"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>viewCount</code>' attribute. * * The number of times the video has been viewed. * * @param[in] value The new value. */ void set_view_count(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("viewCount")); } private: void operator=(const VideoStatistics&); }; // VideoStatistics } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_VIDEO_STATISTICS_H_ <file_sep>/service_apis/youtube/google/youtube_api/live_chat_ban_snippet.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_LIVE_CHAT_BAN_SNIPPET_H_ #define GOOGLE_YOUTUBE_API_LIVE_CHAT_BAN_SNIPPET_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/channel_profile_details.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * No description provided. * * @ingroup DataObject */ class LiveChatBanSnippet : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static LiveChatBanSnippet* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveChatBanSnippet(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveChatBanSnippet(Json::Value* storage); /** * Standard destructor. */ virtual ~LiveChatBanSnippet(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::LiveChatBanSnippet</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::LiveChatBanSnippet"); } /** * Determine if the '<code>banDurationSeconds</code>' attribute was set. * * @return true if the '<code>banDurationSeconds</code>' attribute was set. */ bool has_ban_duration_seconds() const { return Storage().isMember("banDurationSeconds"); } /** * Clears the '<code>banDurationSeconds</code>' attribute. */ void clear_ban_duration_seconds() { MutableStorage()->removeMember("banDurationSeconds"); } /** * Get the value of the '<code>banDurationSeconds</code>' attribute. */ uint64 get_ban_duration_seconds() const { const Json::Value& storage = Storage("banDurationSeconds"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>banDurationSeconds</code>' attribute. * * The duration of a ban, only filled if the ban has type TEMPORARY. * * @param[in] value The new value. */ void set_ban_duration_seconds(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("banDurationSeconds")); } /** * Determine if the '<code>bannedUserDetails</code>' attribute was set. * * @return true if the '<code>bannedUserDetails</code>' attribute was set. */ bool has_banned_user_details() const { return Storage().isMember("bannedUserDetails"); } /** * Clears the '<code>bannedUserDetails</code>' attribute. */ void clear_banned_user_details() { MutableStorage()->removeMember("bannedUserDetails"); } /** * Get a reference to the value of the '<code>bannedUserDetails</code>' * attribute. */ const ChannelProfileDetails get_banned_user_details() const; /** * Gets a reference to a mutable value of the '<code>bannedUserDetails</code>' * property. * @return The result can be modified to change the attribute value. */ ChannelProfileDetails mutable_bannedUserDetails(); /** * Determine if the '<code>liveChatId</code>' attribute was set. * * @return true if the '<code>liveChatId</code>' attribute was set. */ bool has_live_chat_id() const { return Storage().isMember("liveChatId"); } /** * Clears the '<code>liveChatId</code>' attribute. */ void clear_live_chat_id() { MutableStorage()->removeMember("liveChatId"); } /** * Get the value of the '<code>liveChatId</code>' attribute. */ const StringPiece get_live_chat_id() const { const Json::Value& v = Storage("liveChatId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>liveChatId</code>' attribute. * * The chat this ban is pertinent to. * * @param[in] value The new value. */ void set_live_chat_id(const StringPiece& value) { *MutableStorage("liveChatId") = value.data(); } /** * Determine if the '<code>type</code>' attribute was set. * * @return true if the '<code>type</code>' attribute was set. */ bool has_type() const { return Storage().isMember("type"); } /** * Clears the '<code>type</code>' attribute. */ void clear_type() { MutableStorage()->removeMember("type"); } /** * Get the value of the '<code>type</code>' attribute. */ const StringPiece get_type() const { const Json::Value& v = Storage("type"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>type</code>' attribute. * * The type of ban. * * @param[in] value The new value. */ void set_type(const StringPiece& value) { *MutableStorage("type") = value.data(); } private: void operator=(const LiveChatBanSnippet&); }; // LiveChatBanSnippet } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_LIVE_CHAT_BAN_SNIPPET_H_ <file_sep>/service_apis/youtube/google/youtube_api/video_file_details_audio_stream.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_VIDEO_FILE_DETAILS_AUDIO_STREAM_H_ #define GOOGLE_YOUTUBE_API_VIDEO_FILE_DETAILS_AUDIO_STREAM_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Information about an audio stream. * * @ingroup DataObject */ class VideoFileDetailsAudioStream : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static VideoFileDetailsAudioStream* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoFileDetailsAudioStream(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoFileDetailsAudioStream(Json::Value* storage); /** * Standard destructor. */ virtual ~VideoFileDetailsAudioStream(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::VideoFileDetailsAudioStream</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::VideoFileDetailsAudioStream"); } /** * Determine if the '<code>bitrateBps</code>' attribute was set. * * @return true if the '<code>bitrateBps</code>' attribute was set. */ bool has_bitrate_bps() const { return Storage().isMember("bitrateBps"); } /** * Clears the '<code>bitrateBps</code>' attribute. */ void clear_bitrate_bps() { MutableStorage()->removeMember("bitrateBps"); } /** * Get the value of the '<code>bitrateBps</code>' attribute. */ uint64 get_bitrate_bps() const { const Json::Value& storage = Storage("bitrateBps"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>bitrateBps</code>' attribute. * * The audio stream's bitrate, in bits per second. * * @param[in] value The new value. */ void set_bitrate_bps(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("bitrateBps")); } /** * Determine if the '<code>channelCount</code>' attribute was set. * * @return true if the '<code>channelCount</code>' attribute was set. */ bool has_channel_count() const { return Storage().isMember("channelCount"); } /** * Clears the '<code>channelCount</code>' attribute. */ void clear_channel_count() { MutableStorage()->removeMember("channelCount"); } /** * Get the value of the '<code>channelCount</code>' attribute. */ uint32 get_channel_count() const { const Json::Value& storage = Storage("channelCount"); return client::JsonValueToCppValueHelper<uint32 >(storage); } /** * Change the '<code>channelCount</code>' attribute. * * The number of audio channels that the stream contains. * * @param[in] value The new value. */ void set_channel_count(uint32 value) { client::SetJsonValueFromCppValueHelper<uint32 >( value, MutableStorage("channelCount")); } /** * Determine if the '<code>codec</code>' attribute was set. * * @return true if the '<code>codec</code>' attribute was set. */ bool has_codec() const { return Storage().isMember("codec"); } /** * Clears the '<code>codec</code>' attribute. */ void clear_codec() { MutableStorage()->removeMember("codec"); } /** * Get the value of the '<code>codec</code>' attribute. */ const StringPiece get_codec() const { const Json::Value& v = Storage("codec"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>codec</code>' attribute. * * The audio codec that the stream uses. * * @param[in] value The new value. */ void set_codec(const StringPiece& value) { *MutableStorage("codec") = value.data(); } /** * Determine if the '<code>vendor</code>' attribute was set. * * @return true if the '<code>vendor</code>' attribute was set. */ bool has_vendor() const { return Storage().isMember("vendor"); } /** * Clears the '<code>vendor</code>' attribute. */ void clear_vendor() { MutableStorage()->removeMember("vendor"); } /** * Get the value of the '<code>vendor</code>' attribute. */ const StringPiece get_vendor() const { const Json::Value& v = Storage("vendor"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>vendor</code>' attribute. * * A value that uniquely identifies a video vendor. Typically, the value is a * four-letter vendor code. * * @param[in] value The new value. */ void set_vendor(const StringPiece& value) { *MutableStorage("vendor") = value.data(); } private: void operator=(const VideoFileDetailsAudioStream&); }; // VideoFileDetailsAudioStream } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_VIDEO_FILE_DETAILS_AUDIO_STREAM_H_ <file_sep>/service_apis/youtube/google/youtube_api/video_file_details.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_VIDEO_FILE_DETAILS_H_ #define GOOGLE_YOUTUBE_API_VIDEO_FILE_DETAILS_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/video_file_details_audio_stream.h" #include "google/youtube_api/video_file_details_video_stream.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Describes original video file properties, including technical details about * audio and video streams, but also metadata information like content length, * digitization time, or geotagging information. * * @ingroup DataObject */ class VideoFileDetails : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static VideoFileDetails* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoFileDetails(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoFileDetails(Json::Value* storage); /** * Standard destructor. */ virtual ~VideoFileDetails(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::VideoFileDetails</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::VideoFileDetails"); } /** * Determine if the '<code>audioStreams</code>' attribute was set. * * @return true if the '<code>audioStreams</code>' attribute was set. */ bool has_audio_streams() const { return Storage().isMember("audioStreams"); } /** * Clears the '<code>audioStreams</code>' attribute. */ void clear_audio_streams() { MutableStorage()->removeMember("audioStreams"); } /** * Get a reference to the value of the '<code>audioStreams</code>' attribute. */ const client::JsonCppArray<VideoFileDetailsAudioStream > get_audio_streams() const; /** * Gets a reference to a mutable value of the '<code>audioStreams</code>' * property. * * A list of audio streams contained in the uploaded video file. Each item in * the list contains detailed metadata about an audio stream. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<VideoFileDetailsAudioStream > mutable_audioStreams(); /** * Determine if the '<code>bitrateBps</code>' attribute was set. * * @return true if the '<code>bitrateBps</code>' attribute was set. */ bool has_bitrate_bps() const { return Storage().isMember("bitrateBps"); } /** * Clears the '<code>bitrateBps</code>' attribute. */ void clear_bitrate_bps() { MutableStorage()->removeMember("bitrateBps"); } /** * Get the value of the '<code>bitrateBps</code>' attribute. */ uint64 get_bitrate_bps() const { const Json::Value& storage = Storage("bitrateBps"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>bitrateBps</code>' attribute. * * The uploaded video file's combined (video and audio) bitrate in bits per * second. * * @param[in] value The new value. */ void set_bitrate_bps(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("bitrateBps")); } /** * Determine if the '<code>container</code>' attribute was set. * * @return true if the '<code>container</code>' attribute was set. */ bool has_container() const { return Storage().isMember("container"); } /** * Clears the '<code>container</code>' attribute. */ void clear_container() { MutableStorage()->removeMember("container"); } /** * Get the value of the '<code>container</code>' attribute. */ const StringPiece get_container() const { const Json::Value& v = Storage("container"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>container</code>' attribute. * * The uploaded video file's container format. * * @param[in] value The new value. */ void set_container(const StringPiece& value) { *MutableStorage("container") = value.data(); } /** * Determine if the '<code>creationTime</code>' attribute was set. * * @return true if the '<code>creationTime</code>' attribute was set. */ bool has_creation_time() const { return Storage().isMember("creationTime"); } /** * Clears the '<code>creationTime</code>' attribute. */ void clear_creation_time() { MutableStorage()->removeMember("creationTime"); } /** * Get the value of the '<code>creationTime</code>' attribute. */ const StringPiece get_creation_time() const { const Json::Value& v = Storage("creationTime"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>creationTime</code>' attribute. * * The date and time when the uploaded video file was created. The value is * specified in ISO 8601 format. Currently, the following ISO 8601 formats are * supported: * - Date only: YYYY-MM-DD * - Naive time: YYYY-MM-DDTHH:MM:SS * - Time with timezone: YYYY-MM-DDTHH:MM:SS+HH:MM. * * @param[in] value The new value. */ void set_creation_time(const StringPiece& value) { *MutableStorage("creationTime") = value.data(); } /** * Determine if the '<code>durationMs</code>' attribute was set. * * @return true if the '<code>durationMs</code>' attribute was set. */ bool has_duration_ms() const { return Storage().isMember("durationMs"); } /** * Clears the '<code>durationMs</code>' attribute. */ void clear_duration_ms() { MutableStorage()->removeMember("durationMs"); } /** * Get the value of the '<code>durationMs</code>' attribute. */ uint64 get_duration_ms() const { const Json::Value& storage = Storage("durationMs"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>durationMs</code>' attribute. * * The length of the uploaded video in milliseconds. * * @param[in] value The new value. */ void set_duration_ms(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("durationMs")); } /** * Determine if the '<code>fileName</code>' attribute was set. * * @return true if the '<code>fileName</code>' attribute was set. */ bool has_file_name() const { return Storage().isMember("fileName"); } /** * Clears the '<code>fileName</code>' attribute. */ void clear_file_name() { MutableStorage()->removeMember("fileName"); } /** * Get the value of the '<code>fileName</code>' attribute. */ const StringPiece get_file_name() const { const Json::Value& v = Storage("fileName"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>fileName</code>' attribute. * * The uploaded file's name. This field is present whether a video file or * another type of file was uploaded. * * @param[in] value The new value. */ void set_file_name(const StringPiece& value) { *MutableStorage("fileName") = value.data(); } /** * Determine if the '<code>fileSize</code>' attribute was set. * * @return true if the '<code>fileSize</code>' attribute was set. */ bool has_file_size() const { return Storage().isMember("fileSize"); } /** * Clears the '<code>fileSize</code>' attribute. */ void clear_file_size() { MutableStorage()->removeMember("fileSize"); } /** * Get the value of the '<code>fileSize</code>' attribute. */ uint64 get_file_size() const { const Json::Value& storage = Storage("fileSize"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>fileSize</code>' attribute. * * The uploaded file's size in bytes. This field is present whether a video * file or another type of file was uploaded. * * @param[in] value The new value. */ void set_file_size(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("fileSize")); } /** * Determine if the '<code>fileType</code>' attribute was set. * * @return true if the '<code>fileType</code>' attribute was set. */ bool has_file_type() const { return Storage().isMember("fileType"); } /** * Clears the '<code>fileType</code>' attribute. */ void clear_file_type() { MutableStorage()->removeMember("fileType"); } /** * Get the value of the '<code>fileType</code>' attribute. */ const StringPiece get_file_type() const { const Json::Value& v = Storage("fileType"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>fileType</code>' attribute. * * The uploaded file's type as detected by YouTube's video processing engine. * Currently, YouTube only processes video files, but this field is present * whether a video file or another type of file was uploaded. * * @param[in] value The new value. */ void set_file_type(const StringPiece& value) { *MutableStorage("fileType") = value.data(); } /** * Determine if the '<code>videoStreams</code>' attribute was set. * * @return true if the '<code>videoStreams</code>' attribute was set. */ bool has_video_streams() const { return Storage().isMember("videoStreams"); } /** * Clears the '<code>videoStreams</code>' attribute. */ void clear_video_streams() { MutableStorage()->removeMember("videoStreams"); } /** * Get a reference to the value of the '<code>videoStreams</code>' attribute. */ const client::JsonCppArray<VideoFileDetailsVideoStream > get_video_streams() const; /** * Gets a reference to a mutable value of the '<code>videoStreams</code>' * property. * * A list of video streams contained in the uploaded video file. Each item in * the list contains detailed metadata about a video stream. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<VideoFileDetailsVideoStream > mutable_videoStreams(); private: void operator=(const VideoFileDetails&); }; // VideoFileDetails } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_VIDEO_FILE_DETAILS_H_ <file_sep>/service_apis/drive/google/drive_api/file.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Drive API (drive/v2) // Generated from: // Version: v2 // Revision: 20170512 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_DRIVE_API_FILE_H_ #define GOOGLE_DRIVE_API_FILE_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/drive_api/parent_reference.h" #include "google/drive_api/permission.h" #include "google/drive_api/property.h" #include "google/drive_api/user.h" namespace Json { class Value; } // namespace Json namespace google_drive_api { using namespace googleapis; /** * The metadata for a file. * * @ingroup DataObject */ class File : public client::JsonCppData { public: /** * Capabilities the current user has on this file. Each capability corresponds * to a fine-grained action that a user may take. * * @ingroup DataObject */ class FileCapabilities : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static FileCapabilities* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FileCapabilities(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FileCapabilities(Json::Value* storage); /** * Standard destructor. */ virtual ~FileCapabilities(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::FileCapabilities</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::FileCapabilities"); } /** * Determine if the '<code>canAddChildren</code>' attribute was set. * * @return true if the '<code>canAddChildren</code>' attribute was set. */ bool has_can_add_children() const { return Storage().isMember("canAddChildren"); } /** * Clears the '<code>canAddChildren</code>' attribute. */ void clear_can_add_children() { MutableStorage()->removeMember("canAddChildren"); } /** * Get the value of the '<code>canAddChildren</code>' attribute. */ bool get_can_add_children() const { const Json::Value& storage = Storage("canAddChildren"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canAddChildren</code>' attribute. * * Whether the current user can add children to this folder. This is always * false when the item is not a folder. * * @param[in] value The new value. */ void set_can_add_children(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canAddChildren")); } /** * Determine if the '<code>canChangeRestrictedDownload</code>' attribute was * set. * * @return true if the '<code>canChangeRestrictedDownload</code>' attribute * was set. */ bool has_can_change_restricted_download() const { return Storage().isMember("canChangeRestrictedDownload"); } /** * Clears the '<code>canChangeRestrictedDownload</code>' attribute. */ void clear_can_change_restricted_download() { MutableStorage()->removeMember("canChangeRestrictedDownload"); } /** * Get the value of the '<code>canChangeRestrictedDownload</code>' * attribute. */ bool get_can_change_restricted_download() const { const Json::Value& storage = Storage("canChangeRestrictedDownload"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canChangeRestrictedDownload</code>' attribute. * * Whether the current user can change the restricted download label of this * file. * * @param[in] value The new value. */ void set_can_change_restricted_download(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canChangeRestrictedDownload")); } /** * Determine if the '<code>canComment</code>' attribute was set. * * @return true if the '<code>canComment</code>' attribute was set. */ bool has_can_comment() const { return Storage().isMember("canComment"); } /** * Clears the '<code>canComment</code>' attribute. */ void clear_can_comment() { MutableStorage()->removeMember("canComment"); } /** * Get the value of the '<code>canComment</code>' attribute. */ bool get_can_comment() const { const Json::Value& storage = Storage("canComment"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canComment</code>' attribute. * * Whether the current user can comment on this file. * * @param[in] value The new value. */ void set_can_comment(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canComment")); } /** * Determine if the '<code>canCopy</code>' attribute was set. * * @return true if the '<code>canCopy</code>' attribute was set. */ bool has_can_copy() const { return Storage().isMember("canCopy"); } /** * Clears the '<code>canCopy</code>' attribute. */ void clear_can_copy() { MutableStorage()->removeMember("canCopy"); } /** * Get the value of the '<code>canCopy</code>' attribute. */ bool get_can_copy() const { const Json::Value& storage = Storage("canCopy"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canCopy</code>' attribute. * * Whether the current user can copy this file. For a Team Drive item, * whether the current user can copy non-folder descendants of this item, or * this item itself if it is not a folder. * * @param[in] value The new value. */ void set_can_copy(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canCopy")); } /** * Determine if the '<code>canDelete</code>' attribute was set. * * @return true if the '<code>canDelete</code>' attribute was set. */ bool has_can_delete() const { return Storage().isMember("canDelete"); } /** * Clears the '<code>canDelete</code>' attribute. */ void clear_can_delete() { MutableStorage()->removeMember("canDelete"); } /** * Get the value of the '<code>canDelete</code>' attribute. */ bool get_can_delete() const { const Json::Value& storage = Storage("canDelete"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canDelete</code>' attribute. * * Whether the current user can delete this file. * * @param[in] value The new value. */ void set_can_delete(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canDelete")); } /** * Determine if the '<code>canDownload</code>' attribute was set. * * @return true if the '<code>canDownload</code>' attribute was set. */ bool has_can_download() const { return Storage().isMember("canDownload"); } /** * Clears the '<code>canDownload</code>' attribute. */ void clear_can_download() { MutableStorage()->removeMember("canDownload"); } /** * Get the value of the '<code>canDownload</code>' attribute. */ bool get_can_download() const { const Json::Value& storage = Storage("canDownload"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canDownload</code>' attribute. * * Whether the current user can download this file. * * @param[in] value The new value. */ void set_can_download(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canDownload")); } /** * Determine if the '<code>canEdit</code>' attribute was set. * * @return true if the '<code>canEdit</code>' attribute was set. */ bool has_can_edit() const { return Storage().isMember("canEdit"); } /** * Clears the '<code>canEdit</code>' attribute. */ void clear_can_edit() { MutableStorage()->removeMember("canEdit"); } /** * Get the value of the '<code>canEdit</code>' attribute. */ bool get_can_edit() const { const Json::Value& storage = Storage("canEdit"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canEdit</code>' attribute. * * Whether the current user can edit this file. * * @param[in] value The new value. */ void set_can_edit(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canEdit")); } /** * Determine if the '<code>canListChildren</code>' attribute was set. * * @return true if the '<code>canListChildren</code>' attribute was set. */ bool has_can_list_children() const { return Storage().isMember("canListChildren"); } /** * Clears the '<code>canListChildren</code>' attribute. */ void clear_can_list_children() { MutableStorage()->removeMember("canListChildren"); } /** * Get the value of the '<code>canListChildren</code>' attribute. */ bool get_can_list_children() const { const Json::Value& storage = Storage("canListChildren"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canListChildren</code>' attribute. * * Whether the current user can list the children of this folder. This is * always false when the item is not a folder. * * @param[in] value The new value. */ void set_can_list_children(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canListChildren")); } /** * Determine if the '<code>canMoveItemIntoTeamDrive</code>' attribute was * set. * * @return true if the '<code>canMoveItemIntoTeamDrive</code>' attribute was * set. */ bool has_can_move_item_into_team_drive() const { return Storage().isMember("canMoveItemIntoTeamDrive"); } /** * Clears the '<code>canMoveItemIntoTeamDrive</code>' attribute. */ void clear_can_move_item_into_team_drive() { MutableStorage()->removeMember("canMoveItemIntoTeamDrive"); } /** * Get the value of the '<code>canMoveItemIntoTeamDrive</code>' attribute. */ bool get_can_move_item_into_team_drive() const { const Json::Value& storage = Storage("canMoveItemIntoTeamDrive"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canMoveItemIntoTeamDrive</code>' attribute. * * Whether the current user can move this item into a Team Drive. If the * item is in a Team Drive, this field is equivalent to * canMoveTeamDriveItem. * * @param[in] value The new value. */ void set_can_move_item_into_team_drive(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canMoveItemIntoTeamDrive")); } /** * Determine if the '<code>canMoveTeamDriveItem</code>' attribute was set. * * @return true if the '<code>canMoveTeamDriveItem</code>' attribute was * set. */ bool has_can_move_team_drive_item() const { return Storage().isMember("canMoveTeamDriveItem"); } /** * Clears the '<code>canMoveTeamDriveItem</code>' attribute. */ void clear_can_move_team_drive_item() { MutableStorage()->removeMember("canMoveTeamDriveItem"); } /** * Get the value of the '<code>canMoveTeamDriveItem</code>' attribute. */ bool get_can_move_team_drive_item() const { const Json::Value& storage = Storage("canMoveTeamDriveItem"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canMoveTeamDriveItem</code>' attribute. * * Whether the current user can move this Team Drive item by changing its * parent. Note that a request to change the parent for this item may still * fail depending on the new parent that is being added. Only populated for * Team Drive files. * * @param[in] value The new value. */ void set_can_move_team_drive_item(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canMoveTeamDriveItem")); } /** * Determine if the '<code>canReadRevisions</code>' attribute was set. * * @return true if the '<code>canReadRevisions</code>' attribute was set. */ bool has_can_read_revisions() const { return Storage().isMember("canReadRevisions"); } /** * Clears the '<code>canReadRevisions</code>' attribute. */ void clear_can_read_revisions() { MutableStorage()->removeMember("canReadRevisions"); } /** * Get the value of the '<code>canReadRevisions</code>' attribute. */ bool get_can_read_revisions() const { const Json::Value& storage = Storage("canReadRevisions"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canReadRevisions</code>' attribute. * * Whether the current user can read the revisions resource of this file. * For a Team Drive item, whether revisions of non-folder descendants of * this item, or this item itself if it is not a folder, can be read. * * @param[in] value The new value. */ void set_can_read_revisions(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canReadRevisions")); } /** * Determine if the '<code>canReadTeamDrive</code>' attribute was set. * * @return true if the '<code>canReadTeamDrive</code>' attribute was set. */ bool has_can_read_team_drive() const { return Storage().isMember("canReadTeamDrive"); } /** * Clears the '<code>canReadTeamDrive</code>' attribute. */ void clear_can_read_team_drive() { MutableStorage()->removeMember("canReadTeamDrive"); } /** * Get the value of the '<code>canReadTeamDrive</code>' attribute. */ bool get_can_read_team_drive() const { const Json::Value& storage = Storage("canReadTeamDrive"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canReadTeamDrive</code>' attribute. * * Whether the current user can read the Team Drive to which this file * belongs. Only populated for Team Drive files. * * @param[in] value The new value. */ void set_can_read_team_drive(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canReadTeamDrive")); } /** * Determine if the '<code>canRemoveChildren</code>' attribute was set. * * @return true if the '<code>canRemoveChildren</code>' attribute was set. */ bool has_can_remove_children() const { return Storage().isMember("canRemoveChildren"); } /** * Clears the '<code>canRemoveChildren</code>' attribute. */ void clear_can_remove_children() { MutableStorage()->removeMember("canRemoveChildren"); } /** * Get the value of the '<code>canRemoveChildren</code>' attribute. */ bool get_can_remove_children() const { const Json::Value& storage = Storage("canRemoveChildren"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canRemoveChildren</code>' attribute. * * Whether the current user can remove children from this folder. This is * always false when the item is not a folder. * * @param[in] value The new value. */ void set_can_remove_children(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canRemoveChildren")); } /** * Determine if the '<code>canRename</code>' attribute was set. * * @return true if the '<code>canRename</code>' attribute was set. */ bool has_can_rename() const { return Storage().isMember("canRename"); } /** * Clears the '<code>canRename</code>' attribute. */ void clear_can_rename() { MutableStorage()->removeMember("canRename"); } /** * Get the value of the '<code>canRename</code>' attribute. */ bool get_can_rename() const { const Json::Value& storage = Storage("canRename"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canRename</code>' attribute. * * Whether the current user can rename this file. * * @param[in] value The new value. */ void set_can_rename(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canRename")); } /** * Determine if the '<code>canShare</code>' attribute was set. * * @return true if the '<code>canShare</code>' attribute was set. */ bool has_can_share() const { return Storage().isMember("canShare"); } /** * Clears the '<code>canShare</code>' attribute. */ void clear_can_share() { MutableStorage()->removeMember("canShare"); } /** * Get the value of the '<code>canShare</code>' attribute. */ bool get_can_share() const { const Json::Value& storage = Storage("canShare"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canShare</code>' attribute. * * Whether the current user can modify the sharing settings for this file. * * @param[in] value The new value. */ void set_can_share(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canShare")); } /** * Determine if the '<code>canTrash</code>' attribute was set. * * @return true if the '<code>canTrash</code>' attribute was set. */ bool has_can_trash() const { return Storage().isMember("canTrash"); } /** * Clears the '<code>canTrash</code>' attribute. */ void clear_can_trash() { MutableStorage()->removeMember("canTrash"); } /** * Get the value of the '<code>canTrash</code>' attribute. */ bool get_can_trash() const { const Json::Value& storage = Storage("canTrash"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canTrash</code>' attribute. * * Whether the current user can move this file to trash. * * @param[in] value The new value. */ void set_can_trash(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canTrash")); } /** * Determine if the '<code>canUntrash</code>' attribute was set. * * @return true if the '<code>canUntrash</code>' attribute was set. */ bool has_can_untrash() const { return Storage().isMember("canUntrash"); } /** * Clears the '<code>canUntrash</code>' attribute. */ void clear_can_untrash() { MutableStorage()->removeMember("canUntrash"); } /** * Get the value of the '<code>canUntrash</code>' attribute. */ bool get_can_untrash() const { const Json::Value& storage = Storage("canUntrash"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canUntrash</code>' attribute. * * Whether the current user can restore this file from trash. * * @param[in] value The new value. */ void set_can_untrash(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canUntrash")); } private: void operator=(const FileCapabilities&); }; // FileCapabilities /** * Metadata about image media. This will only be present for image types, and * its contents will depend on what can be parsed from the image content. * * @ingroup DataObject */ class FileImageMediaMetadata : public client::JsonCppData { public: /** * Geographic location information stored in the image. * * @ingroup DataObject */ class FileImageMediaMetadataLocation : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static FileImageMediaMetadataLocation* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FileImageMediaMetadataLocation(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FileImageMediaMetadataLocation(Json::Value* storage); /** * Standard destructor. */ virtual ~FileImageMediaMetadataLocation(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::FileImageMediaMetadataLocation</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::FileImageMediaMetadataLocation"); } /** * Determine if the '<code>altitude</code>' attribute was set. * * @return true if the '<code>altitude</code>' attribute was set. */ bool has_altitude() const { return Storage().isMember("altitude"); } /** * Clears the '<code>altitude</code>' attribute. */ void clear_altitude() { MutableStorage()->removeMember("altitude"); } /** * Get the value of the '<code>altitude</code>' attribute. */ double get_altitude() const { const Json::Value& storage = Storage("altitude"); return client::JsonValueToCppValueHelper<double >(storage); } /** * Change the '<code>altitude</code>' attribute. * * The altitude stored in the image. * * @param[in] value The new value. */ void set_altitude(double value) { client::SetJsonValueFromCppValueHelper<double >( value, MutableStorage("altitude")); } /** * Determine if the '<code>latitude</code>' attribute was set. * * @return true if the '<code>latitude</code>' attribute was set. */ bool has_latitude() const { return Storage().isMember("latitude"); } /** * Clears the '<code>latitude</code>' attribute. */ void clear_latitude() { MutableStorage()->removeMember("latitude"); } /** * Get the value of the '<code>latitude</code>' attribute. */ double get_latitude() const { const Json::Value& storage = Storage("latitude"); return client::JsonValueToCppValueHelper<double >(storage); } /** * Change the '<code>latitude</code>' attribute. * * The latitude stored in the image. * * @param[in] value The new value. */ void set_latitude(double value) { client::SetJsonValueFromCppValueHelper<double >( value, MutableStorage("latitude")); } /** * Determine if the '<code>longitude</code>' attribute was set. * * @return true if the '<code>longitude</code>' attribute was set. */ bool has_longitude() const { return Storage().isMember("longitude"); } /** * Clears the '<code>longitude</code>' attribute. */ void clear_longitude() { MutableStorage()->removeMember("longitude"); } /** * Get the value of the '<code>longitude</code>' attribute. */ double get_longitude() const { const Json::Value& storage = Storage("longitude"); return client::JsonValueToCppValueHelper<double >(storage); } /** * Change the '<code>longitude</code>' attribute. * * The longitude stored in the image. * * @param[in] value The new value. */ void set_longitude(double value) { client::SetJsonValueFromCppValueHelper<double >( value, MutableStorage("longitude")); } private: void operator=(const FileImageMediaMetadataLocation&); }; // FileImageMediaMetadataLocation /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static FileImageMediaMetadata* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FileImageMediaMetadata(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FileImageMediaMetadata(Json::Value* storage); /** * Standard destructor. */ virtual ~FileImageMediaMetadata(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::FileImageMediaMetadata</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::FileImageMediaMetadata"); } /** * Determine if the '<code>aperture</code>' attribute was set. * * @return true if the '<code>aperture</code>' attribute was set. */ bool has_aperture() const { return Storage().isMember("aperture"); } /** * Clears the '<code>aperture</code>' attribute. */ void clear_aperture() { MutableStorage()->removeMember("aperture"); } /** * Get the value of the '<code>aperture</code>' attribute. */ float get_aperture() const { const Json::Value& storage = Storage("aperture"); return client::JsonValueToCppValueHelper<float >(storage); } /** * Change the '<code>aperture</code>' attribute. * * The aperture used to create the photo (f-number). * * @param[in] value The new value. */ void set_aperture(float value) { client::SetJsonValueFromCppValueHelper<float >( value, MutableStorage("aperture")); } /** * Determine if the '<code>cameraMake</code>' attribute was set. * * @return true if the '<code>cameraMake</code>' attribute was set. */ bool has_camera_make() const { return Storage().isMember("cameraMake"); } /** * Clears the '<code>cameraMake</code>' attribute. */ void clear_camera_make() { MutableStorage()->removeMember("cameraMake"); } /** * Get the value of the '<code>cameraMake</code>' attribute. */ const StringPiece get_camera_make() const { const Json::Value& v = Storage("cameraMake"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>cameraMake</code>' attribute. * * The make of the camera used to create the photo. * * @param[in] value The new value. */ void set_camera_make(const StringPiece& value) { *MutableStorage("cameraMake") = value.data(); } /** * Determine if the '<code>cameraModel</code>' attribute was set. * * @return true if the '<code>cameraModel</code>' attribute was set. */ bool has_camera_model() const { return Storage().isMember("cameraModel"); } /** * Clears the '<code>cameraModel</code>' attribute. */ void clear_camera_model() { MutableStorage()->removeMember("cameraModel"); } /** * Get the value of the '<code>cameraModel</code>' attribute. */ const StringPiece get_camera_model() const { const Json::Value& v = Storage("cameraModel"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>cameraModel</code>' attribute. * * The model of the camera used to create the photo. * * @param[in] value The new value. */ void set_camera_model(const StringPiece& value) { *MutableStorage("cameraModel") = value.data(); } /** * Determine if the '<code>colorSpace</code>' attribute was set. * * @return true if the '<code>colorSpace</code>' attribute was set. */ bool has_color_space() const { return Storage().isMember("colorSpace"); } /** * Clears the '<code>colorSpace</code>' attribute. */ void clear_color_space() { MutableStorage()->removeMember("colorSpace"); } /** * Get the value of the '<code>colorSpace</code>' attribute. */ const StringPiece get_color_space() const { const Json::Value& v = Storage("colorSpace"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>colorSpace</code>' attribute. * * The color space of the photo. * * @param[in] value The new value. */ void set_color_space(const StringPiece& value) { *MutableStorage("colorSpace") = value.data(); } /** * Determine if the '<code>date</code>' attribute was set. * * @return true if the '<code>date</code>' attribute was set. */ bool has_date() const { return Storage().isMember("date"); } /** * Clears the '<code>date</code>' attribute. */ void clear_date() { MutableStorage()->removeMember("date"); } /** * Get the value of the '<code>date</code>' attribute. */ const StringPiece get_date() const { const Json::Value& v = Storage("date"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>date</code>' attribute. * * The date and time the photo was taken (EXIF format timestamp). * * @param[in] value The new value. */ void set_date(const StringPiece& value) { *MutableStorage("date") = value.data(); } /** * Determine if the '<code>exposureBias</code>' attribute was set. * * @return true if the '<code>exposureBias</code>' attribute was set. */ bool has_exposure_bias() const { return Storage().isMember("exposureBias"); } /** * Clears the '<code>exposureBias</code>' attribute. */ void clear_exposure_bias() { MutableStorage()->removeMember("exposureBias"); } /** * Get the value of the '<code>exposureBias</code>' attribute. */ float get_exposure_bias() const { const Json::Value& storage = Storage("exposureBias"); return client::JsonValueToCppValueHelper<float >(storage); } /** * Change the '<code>exposureBias</code>' attribute. * * The exposure bias of the photo (APEX value). * * @param[in] value The new value. */ void set_exposure_bias(float value) { client::SetJsonValueFromCppValueHelper<float >( value, MutableStorage("exposureBias")); } /** * Determine if the '<code>exposureMode</code>' attribute was set. * * @return true if the '<code>exposureMode</code>' attribute was set. */ bool has_exposure_mode() const { return Storage().isMember("exposureMode"); } /** * Clears the '<code>exposureMode</code>' attribute. */ void clear_exposure_mode() { MutableStorage()->removeMember("exposureMode"); } /** * Get the value of the '<code>exposureMode</code>' attribute. */ const StringPiece get_exposure_mode() const { const Json::Value& v = Storage("exposureMode"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>exposureMode</code>' attribute. * * The exposure mode used to create the photo. * * @param[in] value The new value. */ void set_exposure_mode(const StringPiece& value) { *MutableStorage("exposureMode") = value.data(); } /** * Determine if the '<code>exposureTime</code>' attribute was set. * * @return true if the '<code>exposureTime</code>' attribute was set. */ bool has_exposure_time() const { return Storage().isMember("exposureTime"); } /** * Clears the '<code>exposureTime</code>' attribute. */ void clear_exposure_time() { MutableStorage()->removeMember("exposureTime"); } /** * Get the value of the '<code>exposureTime</code>' attribute. */ float get_exposure_time() const { const Json::Value& storage = Storage("exposureTime"); return client::JsonValueToCppValueHelper<float >(storage); } /** * Change the '<code>exposureTime</code>' attribute. * * The length of the exposure, in seconds. * * @param[in] value The new value. */ void set_exposure_time(float value) { client::SetJsonValueFromCppValueHelper<float >( value, MutableStorage("exposureTime")); } /** * Determine if the '<code>flashUsed</code>' attribute was set. * * @return true if the '<code>flashUsed</code>' attribute was set. */ bool has_flash_used() const { return Storage().isMember("flashUsed"); } /** * Clears the '<code>flashUsed</code>' attribute. */ void clear_flash_used() { MutableStorage()->removeMember("flashUsed"); } /** * Get the value of the '<code>flashUsed</code>' attribute. */ bool get_flash_used() const { const Json::Value& storage = Storage("flashUsed"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>flashUsed</code>' attribute. * * Whether a flash was used to create the photo. * * @param[in] value The new value. */ void set_flash_used(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("flashUsed")); } /** * Determine if the '<code>focalLength</code>' attribute was set. * * @return true if the '<code>focalLength</code>' attribute was set. */ bool has_focal_length() const { return Storage().isMember("focalLength"); } /** * Clears the '<code>focalLength</code>' attribute. */ void clear_focal_length() { MutableStorage()->removeMember("focalLength"); } /** * Get the value of the '<code>focalLength</code>' attribute. */ float get_focal_length() const { const Json::Value& storage = Storage("focalLength"); return client::JsonValueToCppValueHelper<float >(storage); } /** * Change the '<code>focalLength</code>' attribute. * * The focal length used to create the photo, in millimeters. * * @param[in] value The new value. */ void set_focal_length(float value) { client::SetJsonValueFromCppValueHelper<float >( value, MutableStorage("focalLength")); } /** * Determine if the '<code>height</code>' attribute was set. * * @return true if the '<code>height</code>' attribute was set. */ bool has_height() const { return Storage().isMember("height"); } /** * Clears the '<code>height</code>' attribute. */ void clear_height() { MutableStorage()->removeMember("height"); } /** * Get the value of the '<code>height</code>' attribute. */ int32 get_height() const { const Json::Value& storage = Storage("height"); return client::JsonValueToCppValueHelper<int32 >(storage); } /** * Change the '<code>height</code>' attribute. * * The height of the image in pixels. * * @param[in] value The new value. */ void set_height(int32 value) { client::SetJsonValueFromCppValueHelper<int32 >( value, MutableStorage("height")); } /** * Determine if the '<code>isoSpeed</code>' attribute was set. * * @return true if the '<code>isoSpeed</code>' attribute was set. */ bool has_iso_speed() const { return Storage().isMember("isoSpeed"); } /** * Clears the '<code>isoSpeed</code>' attribute. */ void clear_iso_speed() { MutableStorage()->removeMember("isoSpeed"); } /** * Get the value of the '<code>isoSpeed</code>' attribute. */ int32 get_iso_speed() const { const Json::Value& storage = Storage("isoSpeed"); return client::JsonValueToCppValueHelper<int32 >(storage); } /** * Change the '<code>isoSpeed</code>' attribute. * * The ISO speed used to create the photo. * * @param[in] value The new value. */ void set_iso_speed(int32 value) { client::SetJsonValueFromCppValueHelper<int32 >( value, MutableStorage("isoSpeed")); } /** * Determine if the '<code>lens</code>' attribute was set. * * @return true if the '<code>lens</code>' attribute was set. */ bool has_lens() const { return Storage().isMember("lens"); } /** * Clears the '<code>lens</code>' attribute. */ void clear_lens() { MutableStorage()->removeMember("lens"); } /** * Get the value of the '<code>lens</code>' attribute. */ const StringPiece get_lens() const { const Json::Value& v = Storage("lens"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>lens</code>' attribute. * * The lens used to create the photo. * * @param[in] value The new value. */ void set_lens(const StringPiece& value) { *MutableStorage("lens") = value.data(); } /** * Determine if the '<code>location</code>' attribute was set. * * @return true if the '<code>location</code>' attribute was set. */ bool has_location() const { return Storage().isMember("location"); } /** * Clears the '<code>location</code>' attribute. */ void clear_location() { MutableStorage()->removeMember("location"); } /** * Get a reference to the value of the '<code>location</code>' attribute. */ const FileImageMediaMetadataLocation get_location() const { const Json::Value& storage = Storage("location"); return client::JsonValueToCppValueHelper<FileImageMediaMetadataLocation >(storage); } /** * Gets a reference to a mutable value of the '<code>location</code>' * property. * * Geographic location information stored in the image. * * @return The result can be modified to change the attribute value. */ FileImageMediaMetadataLocation mutable_location() { Json::Value* storage = MutableStorage("location"); return client::JsonValueToMutableCppValueHelper<FileImageMediaMetadataLocation >(storage); } /** * Determine if the '<code>maxApertureValue</code>' attribute was set. * * @return true if the '<code>maxApertureValue</code>' attribute was set. */ bool has_max_aperture_value() const { return Storage().isMember("maxApertureValue"); } /** * Clears the '<code>maxApertureValue</code>' attribute. */ void clear_max_aperture_value() { MutableStorage()->removeMember("maxApertureValue"); } /** * Get the value of the '<code>maxApertureValue</code>' attribute. */ float get_max_aperture_value() const { const Json::Value& storage = Storage("maxApertureValue"); return client::JsonValueToCppValueHelper<float >(storage); } /** * Change the '<code>maxApertureValue</code>' attribute. * * The smallest f-number of the lens at the focal length used to create the * photo (APEX value). * * @param[in] value The new value. */ void set_max_aperture_value(float value) { client::SetJsonValueFromCppValueHelper<float >( value, MutableStorage("maxApertureValue")); } /** * Determine if the '<code>meteringMode</code>' attribute was set. * * @return true if the '<code>meteringMode</code>' attribute was set. */ bool has_metering_mode() const { return Storage().isMember("meteringMode"); } /** * Clears the '<code>meteringMode</code>' attribute. */ void clear_metering_mode() { MutableStorage()->removeMember("meteringMode"); } /** * Get the value of the '<code>meteringMode</code>' attribute. */ const StringPiece get_metering_mode() const { const Json::Value& v = Storage("meteringMode"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>meteringMode</code>' attribute. * * The metering mode used to create the photo. * * @param[in] value The new value. */ void set_metering_mode(const StringPiece& value) { *MutableStorage("meteringMode") = value.data(); } /** * Determine if the '<code>rotation</code>' attribute was set. * * @return true if the '<code>rotation</code>' attribute was set. */ bool has_rotation() const { return Storage().isMember("rotation"); } /** * Clears the '<code>rotation</code>' attribute. */ void clear_rotation() { MutableStorage()->removeMember("rotation"); } /** * Get the value of the '<code>rotation</code>' attribute. */ int32 get_rotation() const { const Json::Value& storage = Storage("rotation"); return client::JsonValueToCppValueHelper<int32 >(storage); } /** * Change the '<code>rotation</code>' attribute. * * The rotation in clockwise degrees from the image's original orientation. * * @param[in] value The new value. */ void set_rotation(int32 value) { client::SetJsonValueFromCppValueHelper<int32 >( value, MutableStorage("rotation")); } /** * Determine if the '<code>sensor</code>' attribute was set. * * @return true if the '<code>sensor</code>' attribute was set. */ bool has_sensor() const { return Storage().isMember("sensor"); } /** * Clears the '<code>sensor</code>' attribute. */ void clear_sensor() { MutableStorage()->removeMember("sensor"); } /** * Get the value of the '<code>sensor</code>' attribute. */ const StringPiece get_sensor() const { const Json::Value& v = Storage("sensor"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>sensor</code>' attribute. * * The type of sensor used to create the photo. * * @param[in] value The new value. */ void set_sensor(const StringPiece& value) { *MutableStorage("sensor") = value.data(); } /** * Determine if the '<code>subjectDistance</code>' attribute was set. * * @return true if the '<code>subjectDistance</code>' attribute was set. */ bool has_subject_distance() const { return Storage().isMember("subjectDistance"); } /** * Clears the '<code>subjectDistance</code>' attribute. */ void clear_subject_distance() { MutableStorage()->removeMember("subjectDistance"); } /** * Get the value of the '<code>subjectDistance</code>' attribute. */ int32 get_subject_distance() const { const Json::Value& storage = Storage("subjectDistance"); return client::JsonValueToCppValueHelper<int32 >(storage); } /** * Change the '<code>subjectDistance</code>' attribute. * * The distance to the subject of the photo, in meters. * * @param[in] value The new value. */ void set_subject_distance(int32 value) { client::SetJsonValueFromCppValueHelper<int32 >( value, MutableStorage("subjectDistance")); } /** * Determine if the '<code>whiteBalance</code>' attribute was set. * * @return true if the '<code>whiteBalance</code>' attribute was set. */ bool has_white_balance() const { return Storage().isMember("whiteBalance"); } /** * Clears the '<code>whiteBalance</code>' attribute. */ void clear_white_balance() { MutableStorage()->removeMember("whiteBalance"); } /** * Get the value of the '<code>whiteBalance</code>' attribute. */ const StringPiece get_white_balance() const { const Json::Value& v = Storage("whiteBalance"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>whiteBalance</code>' attribute. * * The white balance mode used to create the photo. * * @param[in] value The new value. */ void set_white_balance(const StringPiece& value) { *MutableStorage("whiteBalance") = value.data(); } /** * Determine if the '<code>width</code>' attribute was set. * * @return true if the '<code>width</code>' attribute was set. */ bool has_width() const { return Storage().isMember("width"); } /** * Clears the '<code>width</code>' attribute. */ void clear_width() { MutableStorage()->removeMember("width"); } /** * Get the value of the '<code>width</code>' attribute. */ int32 get_width() const { const Json::Value& storage = Storage("width"); return client::JsonValueToCppValueHelper<int32 >(storage); } /** * Change the '<code>width</code>' attribute. * * The width of the image in pixels. * * @param[in] value The new value. */ void set_width(int32 value) { client::SetJsonValueFromCppValueHelper<int32 >( value, MutableStorage("width")); } private: void operator=(const FileImageMediaMetadata&); }; // FileImageMediaMetadata /** * Indexable text attributes for the file (can only be written). * * @ingroup DataObject */ class FileIndexableText : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static FileIndexableText* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FileIndexableText(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FileIndexableText(Json::Value* storage); /** * Standard destructor. */ virtual ~FileIndexableText(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::FileIndexableText</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::FileIndexableText"); } /** * Determine if the '<code>text</code>' attribute was set. * * @return true if the '<code>text</code>' attribute was set. */ bool has_text() const { return Storage().isMember("text"); } /** * Clears the '<code>text</code>' attribute. */ void clear_text() { MutableStorage()->removeMember("text"); } /** * Get the value of the '<code>text</code>' attribute. */ const StringPiece get_text() const { const Json::Value& v = Storage("text"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>text</code>' attribute. * * The text to be indexed for this file. * * @param[in] value The new value. */ void set_text(const StringPiece& value) { *MutableStorage("text") = value.data(); } private: void operator=(const FileIndexableText&); }; // FileIndexableText /** * A group of labels for the file. * * @ingroup DataObject */ class FileLabels : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static FileLabels* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FileLabels(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FileLabels(Json::Value* storage); /** * Standard destructor. */ virtual ~FileLabels(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::FileLabels</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::FileLabels"); } /** * Determine if the '<code>hidden</code>' attribute was set. * * @return true if the '<code>hidden</code>' attribute was set. */ bool has_hidden() const { return Storage().isMember("hidden"); } /** * Clears the '<code>hidden</code>' attribute. */ void clear_hidden() { MutableStorage()->removeMember("hidden"); } /** * Get the value of the '<code>hidden</code>' attribute. */ bool get_hidden() const { const Json::Value& storage = Storage("hidden"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>hidden</code>' attribute. * @deprecated * * * Deprecated. * * @param[in] value The new value. */ void set_hidden(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("hidden")); } /** * Determine if the '<code>modified</code>' attribute was set. * * @return true if the '<code>modified</code>' attribute was set. */ bool has_modified() const { return Storage().isMember("modified"); } /** * Clears the '<code>modified</code>' attribute. */ void clear_modified() { MutableStorage()->removeMember("modified"); } /** * Get the value of the '<code>modified</code>' attribute. */ bool get_modified() const { const Json::Value& storage = Storage("modified"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>modified</code>' attribute. * * Whether the file has been modified by this user. * * @param[in] value The new value. */ void set_modified(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("modified")); } /** * Determine if the '<code>restricted</code>' attribute was set. * * @return true if the '<code>restricted</code>' attribute was set. */ bool has_restricted() const { return Storage().isMember("restricted"); } /** * Clears the '<code>restricted</code>' attribute. */ void clear_restricted() { MutableStorage()->removeMember("restricted"); } /** * Get the value of the '<code>restricted</code>' attribute. */ bool get_restricted() const { const Json::Value& storage = Storage("restricted"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>restricted</code>' attribute. * * Whether viewers and commenters are prevented from downloading, printing, * and copying this file. * * @param[in] value The new value. */ void set_restricted(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("restricted")); } /** * Determine if the '<code>starred</code>' attribute was set. * * @return true if the '<code>starred</code>' attribute was set. */ bool has_starred() const { return Storage().isMember("starred"); } /** * Clears the '<code>starred</code>' attribute. */ void clear_starred() { MutableStorage()->removeMember("starred"); } /** * Get the value of the '<code>starred</code>' attribute. */ bool get_starred() const { const Json::Value& storage = Storage("starred"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>starred</code>' attribute. * * Whether this file is starred by the user. * * @param[in] value The new value. */ void set_starred(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("starred")); } /** * Determine if the '<code>trashed</code>' attribute was set. * * @return true if the '<code>trashed</code>' attribute was set. */ bool has_trashed() const { return Storage().isMember("trashed"); } /** * Clears the '<code>trashed</code>' attribute. */ void clear_trashed() { MutableStorage()->removeMember("trashed"); } /** * Get the value of the '<code>trashed</code>' attribute. */ bool get_trashed() const { const Json::Value& storage = Storage("trashed"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>trashed</code>' attribute. * * Whether this file has been trashed. This label applies to all users * accessing the file; however, only owners are allowed to see and untrash * files. * * @param[in] value The new value. */ void set_trashed(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("trashed")); } /** * Determine if the '<code>viewed</code>' attribute was set. * * @return true if the '<code>viewed</code>' attribute was set. */ bool has_viewed() const { return Storage().isMember("viewed"); } /** * Clears the '<code>viewed</code>' attribute. */ void clear_viewed() { MutableStorage()->removeMember("viewed"); } /** * Get the value of the '<code>viewed</code>' attribute. */ bool get_viewed() const { const Json::Value& storage = Storage("viewed"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>viewed</code>' attribute. * * Whether this file has been viewed by this user. * * @param[in] value The new value. */ void set_viewed(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("viewed")); } private: void operator=(const FileLabels&); }; // FileLabels /** * A thumbnail for the file. This will only be used if Drive cannot generate a * standard thumbnail. * * @ingroup DataObject */ class FileThumbnail : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static FileThumbnail* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FileThumbnail(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FileThumbnail(Json::Value* storage); /** * Standard destructor. */ virtual ~FileThumbnail(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::FileThumbnail</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::FileThumbnail"); } /** * Determine if the '<code>image</code>' attribute was set. * * @return true if the '<code>image</code>' attribute was set. */ bool has_image() const { return Storage().isMember("image"); } /** * Clears the '<code>image</code>' attribute. */ void clear_image() { MutableStorage()->removeMember("image"); } /** * Get the value of the '<code>image</code>' attribute. */ const StringPiece get_image() const { const Json::Value& v = Storage("image"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>image</code>' attribute. * * The URL-safe Base64 encoded bytes of the thumbnail image. It should * conform to RFC 4648 section 5. * * @param[in] value The new value. */ void set_image(const StringPiece& value) { *MutableStorage("image") = value.data(); } /** * Determine if the '<code>mimeType</code>' attribute was set. * * @return true if the '<code>mimeType</code>' attribute was set. */ bool has_mime_type() const { return Storage().isMember("mimeType"); } /** * Clears the '<code>mimeType</code>' attribute. */ void clear_mime_type() { MutableStorage()->removeMember("mimeType"); } /** * Get the value of the '<code>mimeType</code>' attribute. */ const StringPiece get_mime_type() const { const Json::Value& v = Storage("mimeType"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>mimeType</code>' attribute. * * The MIME type of the thumbnail. * * @param[in] value The new value. */ void set_mime_type(const StringPiece& value) { *MutableStorage("mimeType") = value.data(); } private: void operator=(const FileThumbnail&); }; // FileThumbnail /** * Metadata about video media. This will only be present for video types. * * @ingroup DataObject */ class FileVideoMediaMetadata : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static FileVideoMediaMetadata* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FileVideoMediaMetadata(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit FileVideoMediaMetadata(Json::Value* storage); /** * Standard destructor. */ virtual ~FileVideoMediaMetadata(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::FileVideoMediaMetadata</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::FileVideoMediaMetadata"); } /** * Determine if the '<code>durationMillis</code>' attribute was set. * * @return true if the '<code>durationMillis</code>' attribute was set. */ bool has_duration_millis() const { return Storage().isMember("durationMillis"); } /** * Clears the '<code>durationMillis</code>' attribute. */ void clear_duration_millis() { MutableStorage()->removeMember("durationMillis"); } /** * Get the value of the '<code>durationMillis</code>' attribute. */ int64 get_duration_millis() const { const Json::Value& storage = Storage("durationMillis"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>durationMillis</code>' attribute. * * The duration of the video in milliseconds. * * @param[in] value The new value. */ void set_duration_millis(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("durationMillis")); } /** * Determine if the '<code>height</code>' attribute was set. * * @return true if the '<code>height</code>' attribute was set. */ bool has_height() const { return Storage().isMember("height"); } /** * Clears the '<code>height</code>' attribute. */ void clear_height() { MutableStorage()->removeMember("height"); } /** * Get the value of the '<code>height</code>' attribute. */ int32 get_height() const { const Json::Value& storage = Storage("height"); return client::JsonValueToCppValueHelper<int32 >(storage); } /** * Change the '<code>height</code>' attribute. * * The height of the video in pixels. * * @param[in] value The new value. */ void set_height(int32 value) { client::SetJsonValueFromCppValueHelper<int32 >( value, MutableStorage("height")); } /** * Determine if the '<code>width</code>' attribute was set. * * @return true if the '<code>width</code>' attribute was set. */ bool has_width() const { return Storage().isMember("width"); } /** * Clears the '<code>width</code>' attribute. */ void clear_width() { MutableStorage()->removeMember("width"); } /** * Get the value of the '<code>width</code>' attribute. */ int32 get_width() const { const Json::Value& storage = Storage("width"); return client::JsonValueToCppValueHelper<int32 >(storage); } /** * Change the '<code>width</code>' attribute. * * The width of the video in pixels. * * @param[in] value The new value. */ void set_width(int32 value) { client::SetJsonValueFromCppValueHelper<int32 >( value, MutableStorage("width")); } private: void operator=(const FileVideoMediaMetadata&); }; // FileVideoMediaMetadata /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static File* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit File(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit File(Json::Value* storage); /** * Standard destructor. */ virtual ~File(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::File</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::File"); } /** * Determine if the '<code>alternateLink</code>' attribute was set. * * @return true if the '<code>alternateLink</code>' attribute was set. */ bool has_alternate_link() const { return Storage().isMember("alternateLink"); } /** * Clears the '<code>alternateLink</code>' attribute. */ void clear_alternate_link() { MutableStorage()->removeMember("alternateLink"); } /** * Get the value of the '<code>alternateLink</code>' attribute. */ const StringPiece get_alternate_link() const { const Json::Value& v = Storage("alternateLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>alternateLink</code>' attribute. * * A link for opening the file in a relevant Google editor or viewer. * * @param[in] value The new value. */ void set_alternate_link(const StringPiece& value) { *MutableStorage("alternateLink") = value.data(); } /** * Determine if the '<code>appDataContents</code>' attribute was set. * * @return true if the '<code>appDataContents</code>' attribute was set. */ bool has_app_data_contents() const { return Storage().isMember("appDataContents"); } /** * Clears the '<code>appDataContents</code>' attribute. */ void clear_app_data_contents() { MutableStorage()->removeMember("appDataContents"); } /** * Get the value of the '<code>appDataContents</code>' attribute. */ bool get_app_data_contents() const { const Json::Value& storage = Storage("appDataContents"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>appDataContents</code>' attribute. * * Whether this file is in the Application Data folder. * * @param[in] value The new value. */ void set_app_data_contents(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("appDataContents")); } /** * Determine if the '<code>canComment</code>' attribute was set. * * @return true if the '<code>canComment</code>' attribute was set. */ bool has_can_comment() const { return Storage().isMember("canComment"); } /** * Clears the '<code>canComment</code>' attribute. */ void clear_can_comment() { MutableStorage()->removeMember("canComment"); } /** * Get the value of the '<code>canComment</code>' attribute. */ bool get_can_comment() const { const Json::Value& storage = Storage("canComment"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canComment</code>' attribute. * @deprecated * * * Deprecated: use capabilities/canComment. * * @param[in] value The new value. */ void set_can_comment(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canComment")); } /** * Determine if the '<code>canReadRevisions</code>' attribute was set. * * @return true if the '<code>canReadRevisions</code>' attribute was set. */ bool has_can_read_revisions() const { return Storage().isMember("canReadRevisions"); } /** * Clears the '<code>canReadRevisions</code>' attribute. */ void clear_can_read_revisions() { MutableStorage()->removeMember("canReadRevisions"); } /** * Get the value of the '<code>canReadRevisions</code>' attribute. */ bool get_can_read_revisions() const { const Json::Value& storage = Storage("canReadRevisions"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>canReadRevisions</code>' attribute. * @deprecated * * * Deprecated: use capabilities/canReadRevisions. * * @param[in] value The new value. */ void set_can_read_revisions(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("canReadRevisions")); } /** * Determine if the '<code>capabilities</code>' attribute was set. * * @return true if the '<code>capabilities</code>' attribute was set. */ bool has_capabilities() const { return Storage().isMember("capabilities"); } /** * Clears the '<code>capabilities</code>' attribute. */ void clear_capabilities() { MutableStorage()->removeMember("capabilities"); } /** * Get a reference to the value of the '<code>capabilities</code>' attribute. */ const FileCapabilities get_capabilities() const { const Json::Value& storage = Storage("capabilities"); return client::JsonValueToCppValueHelper<FileCapabilities >(storage); } /** * Gets a reference to a mutable value of the '<code>capabilities</code>' * property. * * Capabilities the current user has on this file. Each capability corresponds * to a fine-grained action that a user may take. * * @return The result can be modified to change the attribute value. */ FileCapabilities mutable_capabilities() { Json::Value* storage = MutableStorage("capabilities"); return client::JsonValueToMutableCppValueHelper<FileCapabilities >(storage); } /** * Determine if the '<code>copyable</code>' attribute was set. * * @return true if the '<code>copyable</code>' attribute was set. */ bool has_copyable() const { return Storage().isMember("copyable"); } /** * Clears the '<code>copyable</code>' attribute. */ void clear_copyable() { MutableStorage()->removeMember("copyable"); } /** * Get the value of the '<code>copyable</code>' attribute. */ bool get_copyable() const { const Json::Value& storage = Storage("copyable"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>copyable</code>' attribute. * @deprecated * * * Deprecated: use capabilities/canCopy. * * @param[in] value The new value. */ void set_copyable(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("copyable")); } /** * Determine if the '<code>createdDate</code>' attribute was set. * * @return true if the '<code>createdDate</code>' attribute was set. */ bool has_created_date() const { return Storage().isMember("createdDate"); } /** * Clears the '<code>createdDate</code>' attribute. */ void clear_created_date() { MutableStorage()->removeMember("createdDate"); } /** * Get the value of the '<code>createdDate</code>' attribute. */ client::DateTime get_created_date() const { const Json::Value& storage = Storage("createdDate"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>createdDate</code>' attribute. * * Create time for this file (formatted RFC 3339 timestamp). * * @param[in] value The new value. */ void set_created_date(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("createdDate")); } /** * Determine if the '<code>defaultOpenWithLink</code>' attribute was set. * * @return true if the '<code>defaultOpenWithLink</code>' attribute was set. */ bool has_default_open_with_link() const { return Storage().isMember("defaultOpenWithLink"); } /** * Clears the '<code>defaultOpenWithLink</code>' attribute. */ void clear_default_open_with_link() { MutableStorage()->removeMember("defaultOpenWithLink"); } /** * Get the value of the '<code>defaultOpenWithLink</code>' attribute. */ const StringPiece get_default_open_with_link() const { const Json::Value& v = Storage("defaultOpenWithLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>defaultOpenWithLink</code>' attribute. * * A link to open this file with the user's default app for this file. Only * populated when the drive.apps.readonly scope is used. * * @param[in] value The new value. */ void set_default_open_with_link(const StringPiece& value) { *MutableStorage("defaultOpenWithLink") = value.data(); } /** * Determine if the '<code>description</code>' attribute was set. * * @return true if the '<code>description</code>' attribute was set. */ bool has_description() const { return Storage().isMember("description"); } /** * Clears the '<code>description</code>' attribute. */ void clear_description() { MutableStorage()->removeMember("description"); } /** * Get the value of the '<code>description</code>' attribute. */ const StringPiece get_description() const { const Json::Value& v = Storage("description"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>description</code>' attribute. * * A short description of the file. * * @param[in] value The new value. */ void set_description(const StringPiece& value) { *MutableStorage("description") = value.data(); } /** * Determine if the '<code>downloadUrl</code>' attribute was set. * * @return true if the '<code>downloadUrl</code>' attribute was set. */ bool has_download_url() const { return Storage().isMember("downloadUrl"); } /** * Clears the '<code>downloadUrl</code>' attribute. */ void clear_download_url() { MutableStorage()->removeMember("downloadUrl"); } /** * Get the value of the '<code>downloadUrl</code>' attribute. */ const StringPiece get_download_url() const { const Json::Value& v = Storage("downloadUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>downloadUrl</code>' attribute. * @param[in] value The new value. */ void set_download_url(const StringPiece& value) { *MutableStorage("downloadUrl") = value.data(); } /** * Determine if the '<code>editable</code>' attribute was set. * * @return true if the '<code>editable</code>' attribute was set. */ bool has_editable() const { return Storage().isMember("editable"); } /** * Clears the '<code>editable</code>' attribute. */ void clear_editable() { MutableStorage()->removeMember("editable"); } /** * Get the value of the '<code>editable</code>' attribute. */ bool get_editable() const { const Json::Value& storage = Storage("editable"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>editable</code>' attribute. * @deprecated * * * Deprecated: use capabilities/canEdit. * * @param[in] value The new value. */ void set_editable(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("editable")); } /** * Determine if the '<code>embedLink</code>' attribute was set. * * @return true if the '<code>embedLink</code>' attribute was set. */ bool has_embed_link() const { return Storage().isMember("embedLink"); } /** * Clears the '<code>embedLink</code>' attribute. */ void clear_embed_link() { MutableStorage()->removeMember("embedLink"); } /** * Get the value of the '<code>embedLink</code>' attribute. */ const StringPiece get_embed_link() const { const Json::Value& v = Storage("embedLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>embedLink</code>' attribute. * * A link for embedding the file. * * @param[in] value The new value. */ void set_embed_link(const StringPiece& value) { *MutableStorage("embedLink") = value.data(); } /** * Determine if the '<code>etag</code>' attribute was set. * * @return true if the '<code>etag</code>' attribute was set. */ bool has_etag() const { return Storage().isMember("etag"); } /** * Clears the '<code>etag</code>' attribute. */ void clear_etag() { MutableStorage()->removeMember("etag"); } /** * Get the value of the '<code>etag</code>' attribute. */ const StringPiece get_etag() const { const Json::Value& v = Storage("etag"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>etag</code>' attribute. * * ETag of the file. * * @param[in] value The new value. */ void set_etag(const StringPiece& value) { *MutableStorage("etag") = value.data(); } /** * Determine if the '<code>explicitlyTrashed</code>' attribute was set. * * @return true if the '<code>explicitlyTrashed</code>' attribute was set. */ bool has_explicitly_trashed() const { return Storage().isMember("explicitlyTrashed"); } /** * Clears the '<code>explicitlyTrashed</code>' attribute. */ void clear_explicitly_trashed() { MutableStorage()->removeMember("explicitlyTrashed"); } /** * Get the value of the '<code>explicitlyTrashed</code>' attribute. */ bool get_explicitly_trashed() const { const Json::Value& storage = Storage("explicitlyTrashed"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>explicitlyTrashed</code>' attribute. * * Whether this file has been explicitly trashed, as opposed to recursively * trashed. * * @param[in] value The new value. */ void set_explicitly_trashed(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("explicitlyTrashed")); } /** * Determine if the '<code>exportLinks</code>' attribute was set. * * @return true if the '<code>exportLinks</code>' attribute was set. */ bool has_export_links() const { return Storage().isMember("exportLinks"); } /** * Clears the '<code>exportLinks</code>' attribute. */ void clear_export_links() { MutableStorage()->removeMember("exportLinks"); } /** * Get a reference to the value of the '<code>exportLinks</code>' attribute. */ const client::JsonCppAssociativeArray<string > get_export_links() const { const Json::Value& storage = Storage("exportLinks"); return client::JsonValueToCppValueHelper<client::JsonCppAssociativeArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>exportLinks</code>' * property. * * Links for exporting Google Docs to specific formats. * * @return The result can be modified to change the attribute value. */ client::JsonCppAssociativeArray<string > mutable_exportLinks() { Json::Value* storage = MutableStorage("exportLinks"); return client::JsonValueToMutableCppValueHelper<client::JsonCppAssociativeArray<string > >(storage); } /** * Determine if the '<code>fileExtension</code>' attribute was set. * * @return true if the '<code>fileExtension</code>' attribute was set. */ bool has_file_extension() const { return Storage().isMember("fileExtension"); } /** * Clears the '<code>fileExtension</code>' attribute. */ void clear_file_extension() { MutableStorage()->removeMember("fileExtension"); } /** * Get the value of the '<code>fileExtension</code>' attribute. */ const StringPiece get_file_extension() const { const Json::Value& v = Storage("fileExtension"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>fileExtension</code>' attribute. * * The final component of fullFileExtension with trailing text that does not * appear to be part of the extension removed. This field is only populated * for files with content stored in Drive; it is not populated for Google Docs * or shortcut files. * * @param[in] value The new value. */ void set_file_extension(const StringPiece& value) { *MutableStorage("fileExtension") = value.data(); } /** * Determine if the '<code>fileSize</code>' attribute was set. * * @return true if the '<code>fileSize</code>' attribute was set. */ bool has_file_size() const { return Storage().isMember("fileSize"); } /** * Clears the '<code>fileSize</code>' attribute. */ void clear_file_size() { MutableStorage()->removeMember("fileSize"); } /** * Get the value of the '<code>fileSize</code>' attribute. */ int64 get_file_size() const { const Json::Value& storage = Storage("fileSize"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>fileSize</code>' attribute. * * The size of the file in bytes. This field is only populated for files with * content stored in Drive; it is not populated for Google Docs or shortcut * files. * * @param[in] value The new value. */ void set_file_size(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("fileSize")); } /** * Determine if the '<code>folderColorRgb</code>' attribute was set. * * @return true if the '<code>folderColorRgb</code>' attribute was set. */ bool has_folder_color_rgb() const { return Storage().isMember("folderColorRgb"); } /** * Clears the '<code>folderColorRgb</code>' attribute. */ void clear_folder_color_rgb() { MutableStorage()->removeMember("folderColorRgb"); } /** * Get the value of the '<code>folderColorRgb</code>' attribute. */ const StringPiece get_folder_color_rgb() const { const Json::Value& v = Storage("folderColorRgb"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>folderColorRgb</code>' attribute. * * Folder color as an RGB hex string if the file is a folder. The list of * supported colors is available in the folderColorPalette field of the About * resource. If an unsupported color is specified, it will be changed to the * closest color in the palette. Not populated for Team Drive files. * * @param[in] value The new value. */ void set_folder_color_rgb(const StringPiece& value) { *MutableStorage("folderColorRgb") = value.data(); } /** * Determine if the '<code>fullFileExtension</code>' attribute was set. * * @return true if the '<code>fullFileExtension</code>' attribute was set. */ bool has_full_file_extension() const { return Storage().isMember("fullFileExtension"); } /** * Clears the '<code>fullFileExtension</code>' attribute. */ void clear_full_file_extension() { MutableStorage()->removeMember("fullFileExtension"); } /** * Get the value of the '<code>fullFileExtension</code>' attribute. */ const StringPiece get_full_file_extension() const { const Json::Value& v = Storage("fullFileExtension"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>fullFileExtension</code>' attribute. * * The full file extension; extracted from the title. May contain multiple * concatenated extensions, such as "tar.gz". Removing an extension from the * title does not clear this field; however, changing the extension on the * title does update this field. This field is only populated for files with * content stored in Drive; it is not populated for Google Docs or shortcut * files. * * @param[in] value The new value. */ void set_full_file_extension(const StringPiece& value) { *MutableStorage("fullFileExtension") = value.data(); } /** * Determine if the '<code>hasAugmentedPermissions</code>' attribute was set. * * @return true if the '<code>hasAugmentedPermissions</code>' attribute was * set. */ bool has_has_augmented_permissions() const { return Storage().isMember("hasAugmentedPermissions"); } /** * Clears the '<code>hasAugmentedPermissions</code>' attribute. */ void clear_has_augmented_permissions() { MutableStorage()->removeMember("hasAugmentedPermissions"); } /** * Get the value of the '<code>hasAugmentedPermissions</code>' attribute. */ bool get_has_augmented_permissions() const { const Json::Value& storage = Storage("hasAugmentedPermissions"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>hasAugmentedPermissions</code>' attribute. * * Whether any users are granted file access directly on this file. This field * is only populated for Team Drive files. * * @param[in] value The new value. */ void set_has_augmented_permissions(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("hasAugmentedPermissions")); } /** * Determine if the '<code>hasThumbnail</code>' attribute was set. * * @return true if the '<code>hasThumbnail</code>' attribute was set. */ bool has_has_thumbnail() const { return Storage().isMember("hasThumbnail"); } /** * Clears the '<code>hasThumbnail</code>' attribute. */ void clear_has_thumbnail() { MutableStorage()->removeMember("hasThumbnail"); } /** * Get the value of the '<code>hasThumbnail</code>' attribute. */ bool get_has_thumbnail() const { const Json::Value& storage = Storage("hasThumbnail"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>hasThumbnail</code>' attribute. * * Whether this file has a thumbnail. This does not indicate whether the * requesting app has access to the thumbnail. To check access, look for the * presence of the thumbnailLink field. * * @param[in] value The new value. */ void set_has_thumbnail(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("hasThumbnail")); } /** * Determine if the '<code>headRevisionId</code>' attribute was set. * * @return true if the '<code>headRevisionId</code>' attribute was set. */ bool has_head_revision_id() const { return Storage().isMember("headRevisionId"); } /** * Clears the '<code>headRevisionId</code>' attribute. */ void clear_head_revision_id() { MutableStorage()->removeMember("headRevisionId"); } /** * Get the value of the '<code>headRevisionId</code>' attribute. */ const StringPiece get_head_revision_id() const { const Json::Value& v = Storage("headRevisionId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>headRevisionId</code>' attribute. * * The ID of the file's head revision. This field is only populated for files * with content stored in Drive; it is not populated for Google Docs or * shortcut files. * * @param[in] value The new value. */ void set_head_revision_id(const StringPiece& value) { *MutableStorage("headRevisionId") = value.data(); } /** * Determine if the '<code>iconLink</code>' attribute was set. * * @return true if the '<code>iconLink</code>' attribute was set. */ bool has_icon_link() const { return Storage().isMember("iconLink"); } /** * Clears the '<code>iconLink</code>' attribute. */ void clear_icon_link() { MutableStorage()->removeMember("iconLink"); } /** * Get the value of the '<code>iconLink</code>' attribute. */ const StringPiece get_icon_link() const { const Json::Value& v = Storage("iconLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>iconLink</code>' attribute. * * A link to the file's icon. * * @param[in] value The new value. */ void set_icon_link(const StringPiece& value) { *MutableStorage("iconLink") = value.data(); } /** * Determine if the '<code>id</code>' attribute was set. * * @return true if the '<code>id</code>' attribute was set. */ bool has_id() const { return Storage().isMember("id"); } /** * Clears the '<code>id</code>' attribute. */ void clear_id() { MutableStorage()->removeMember("id"); } /** * Get the value of the '<code>id</code>' attribute. */ const StringPiece get_id() const { const Json::Value& v = Storage("id"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>id</code>' attribute. * * The ID of the file. * * @param[in] value The new value. */ void set_id(const StringPiece& value) { *MutableStorage("id") = value.data(); } /** * Determine if the '<code>imageMediaMetadata</code>' attribute was set. * * @return true if the '<code>imageMediaMetadata</code>' attribute was set. */ bool has_image_media_metadata() const { return Storage().isMember("imageMediaMetadata"); } /** * Clears the '<code>imageMediaMetadata</code>' attribute. */ void clear_image_media_metadata() { MutableStorage()->removeMember("imageMediaMetadata"); } /** * Get a reference to the value of the '<code>imageMediaMetadata</code>' * attribute. */ const FileImageMediaMetadata get_image_media_metadata() const { const Json::Value& storage = Storage("imageMediaMetadata"); return client::JsonValueToCppValueHelper<FileImageMediaMetadata >(storage); } /** * Gets a reference to a mutable value of the * '<code>imageMediaMetadata</code>' property. * * Metadata about image media. This will only be present for image types, and * its contents will depend on what can be parsed from the image content. * * @return The result can be modified to change the attribute value. */ FileImageMediaMetadata mutable_imageMediaMetadata() { Json::Value* storage = MutableStorage("imageMediaMetadata"); return client::JsonValueToMutableCppValueHelper<FileImageMediaMetadata >(storage); } /** * Determine if the '<code>indexableText</code>' attribute was set. * * @return true if the '<code>indexableText</code>' attribute was set. */ bool has_indexable_text() const { return Storage().isMember("indexableText"); } /** * Clears the '<code>indexableText</code>' attribute. */ void clear_indexable_text() { MutableStorage()->removeMember("indexableText"); } /** * Get a reference to the value of the '<code>indexableText</code>' attribute. */ const FileIndexableText get_indexable_text() const { const Json::Value& storage = Storage("indexableText"); return client::JsonValueToCppValueHelper<FileIndexableText >(storage); } /** * Gets a reference to a mutable value of the '<code>indexableText</code>' * property. * * Indexable text attributes for the file (can only be written). * * @return The result can be modified to change the attribute value. */ FileIndexableText mutable_indexableText() { Json::Value* storage = MutableStorage("indexableText"); return client::JsonValueToMutableCppValueHelper<FileIndexableText >(storage); } /** * Determine if the '<code>isAppAuthorized</code>' attribute was set. * * @return true if the '<code>isAppAuthorized</code>' attribute was set. */ bool has_is_app_authorized() const { return Storage().isMember("isAppAuthorized"); } /** * Clears the '<code>isAppAuthorized</code>' attribute. */ void clear_is_app_authorized() { MutableStorage()->removeMember("isAppAuthorized"); } /** * Get the value of the '<code>isAppAuthorized</code>' attribute. */ bool get_is_app_authorized() const { const Json::Value& storage = Storage("isAppAuthorized"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>isAppAuthorized</code>' attribute. * * Whether the file was created or opened by the requesting app. * * @param[in] value The new value. */ void set_is_app_authorized(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("isAppAuthorized")); } /** * Determine if the '<code>kind</code>' attribute was set. * * @return true if the '<code>kind</code>' attribute was set. */ bool has_kind() const { return Storage().isMember("kind"); } /** * Clears the '<code>kind</code>' attribute. */ void clear_kind() { MutableStorage()->removeMember("kind"); } /** * Get the value of the '<code>kind</code>' attribute. */ const StringPiece get_kind() const { const Json::Value& v = Storage("kind"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kind</code>' attribute. * * The type of file. This is always drive#file. * * @param[in] value The new value. */ void set_kind(const StringPiece& value) { *MutableStorage("kind") = value.data(); } /** * Determine if the '<code>labels</code>' attribute was set. * * @return true if the '<code>labels</code>' attribute was set. */ bool has_labels() const { return Storage().isMember("labels"); } /** * Clears the '<code>labels</code>' attribute. */ void clear_labels() { MutableStorage()->removeMember("labels"); } /** * Get a reference to the value of the '<code>labels</code>' attribute. */ const FileLabels get_labels() const { const Json::Value& storage = Storage("labels"); return client::JsonValueToCppValueHelper<FileLabels >(storage); } /** * Gets a reference to a mutable value of the '<code>labels</code>' property. * * A group of labels for the file. * * @return The result can be modified to change the attribute value. */ FileLabels mutable_labels() { Json::Value* storage = MutableStorage("labels"); return client::JsonValueToMutableCppValueHelper<FileLabels >(storage); } /** * Determine if the '<code>lastModifyingUser</code>' attribute was set. * * @return true if the '<code>lastModifyingUser</code>' attribute was set. */ bool has_last_modifying_user() const { return Storage().isMember("lastModifyingUser"); } /** * Clears the '<code>lastModifyingUser</code>' attribute. */ void clear_last_modifying_user() { MutableStorage()->removeMember("lastModifyingUser"); } /** * Get a reference to the value of the '<code>lastModifyingUser</code>' * attribute. */ const User get_last_modifying_user() const; /** * Gets a reference to a mutable value of the '<code>lastModifyingUser</code>' * property. * * The last user to modify this file. * * @return The result can be modified to change the attribute value. */ User mutable_lastModifyingUser(); /** * Determine if the '<code>lastModifyingUserName</code>' attribute was set. * * @return true if the '<code>lastModifyingUserName</code>' attribute was set. */ bool has_last_modifying_user_name() const { return Storage().isMember("lastModifyingUserName"); } /** * Clears the '<code>lastModifyingUserName</code>' attribute. */ void clear_last_modifying_user_name() { MutableStorage()->removeMember("lastModifyingUserName"); } /** * Get the value of the '<code>lastModifyingUserName</code>' attribute. */ const StringPiece get_last_modifying_user_name() const { const Json::Value& v = Storage("lastModifyingUserName"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>lastModifyingUserName</code>' attribute. * * Name of the last user to modify this file. * * @param[in] value The new value. */ void set_last_modifying_user_name(const StringPiece& value) { *MutableStorage("lastModifyingUserName") = value.data(); } /** * Determine if the '<code>lastViewedByMeDate</code>' attribute was set. * * @return true if the '<code>lastViewedByMeDate</code>' attribute was set. */ bool has_last_viewed_by_me_date() const { return Storage().isMember("lastViewedByMeDate"); } /** * Clears the '<code>lastViewedByMeDate</code>' attribute. */ void clear_last_viewed_by_me_date() { MutableStorage()->removeMember("lastViewedByMeDate"); } /** * Get the value of the '<code>lastViewedByMeDate</code>' attribute. */ client::DateTime get_last_viewed_by_me_date() const { const Json::Value& storage = Storage("lastViewedByMeDate"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>lastViewedByMeDate</code>' attribute. * * Last time this file was viewed by the user (formatted RFC 3339 timestamp). * * @param[in] value The new value. */ void set_last_viewed_by_me_date(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("lastViewedByMeDate")); } /** * Determine if the '<code>markedViewedByMeDate</code>' attribute was set. * * @return true if the '<code>markedViewedByMeDate</code>' attribute was set. */ bool has_marked_viewed_by_me_date() const { return Storage().isMember("markedViewedByMeDate"); } /** * Clears the '<code>markedViewedByMeDate</code>' attribute. */ void clear_marked_viewed_by_me_date() { MutableStorage()->removeMember("markedViewedByMeDate"); } /** * Get the value of the '<code>markedViewedByMeDate</code>' attribute. */ client::DateTime get_marked_viewed_by_me_date() const { const Json::Value& storage = Storage("markedViewedByMeDate"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>markedViewedByMeDate</code>' attribute. * @deprecated * * * Deprecated. * * @param[in] value The new value. */ void set_marked_viewed_by_me_date(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("markedViewedByMeDate")); } /** * Determine if the '<code>md5Checksum</code>' attribute was set. * * @return true if the '<code>md5Checksum</code>' attribute was set. */ bool has_md5_checksum() const { return Storage().isMember("md5Checksum"); } /** * Clears the '<code>md5Checksum</code>' attribute. */ void clear_md5_checksum() { MutableStorage()->removeMember("md5Checksum"); } /** * Get the value of the '<code>md5Checksum</code>' attribute. */ const StringPiece get_md5_checksum() const { const Json::Value& v = Storage("md5Checksum"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>md5Checksum</code>' attribute. * * An MD5 checksum for the content of this file. This field is only populated * for files with content stored in Drive; it is not populated for Google Docs * or shortcut files. * * @param[in] value The new value. */ void set_md5_checksum(const StringPiece& value) { *MutableStorage("md5Checksum") = value.data(); } /** * Determine if the '<code>mimeType</code>' attribute was set. * * @return true if the '<code>mimeType</code>' attribute was set. */ bool has_mime_type() const { return Storage().isMember("mimeType"); } /** * Clears the '<code>mimeType</code>' attribute. */ void clear_mime_type() { MutableStorage()->removeMember("mimeType"); } /** * Get the value of the '<code>mimeType</code>' attribute. */ const StringPiece get_mime_type() const { const Json::Value& v = Storage("mimeType"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>mimeType</code>' attribute. * * The MIME type of the file. This is only mutable on update when uploading * new content. This field can be left blank, and the mimetype will be * determined from the uploaded content's MIME type. * * @param[in] value The new value. */ void set_mime_type(const StringPiece& value) { *MutableStorage("mimeType") = value.data(); } /** * Determine if the '<code>modifiedByMeDate</code>' attribute was set. * * @return true if the '<code>modifiedByMeDate</code>' attribute was set. */ bool has_modified_by_me_date() const { return Storage().isMember("modifiedByMeDate"); } /** * Clears the '<code>modifiedByMeDate</code>' attribute. */ void clear_modified_by_me_date() { MutableStorage()->removeMember("modifiedByMeDate"); } /** * Get the value of the '<code>modifiedByMeDate</code>' attribute. */ client::DateTime get_modified_by_me_date() const { const Json::Value& storage = Storage("modifiedByMeDate"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>modifiedByMeDate</code>' attribute. * * Last time this file was modified by the user (formatted RFC 3339 * timestamp). Note that setting modifiedDate will also update the * modifiedByMe date for the user which set the date. * * @param[in] value The new value. */ void set_modified_by_me_date(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("modifiedByMeDate")); } /** * Determine if the '<code>modifiedDate</code>' attribute was set. * * @return true if the '<code>modifiedDate</code>' attribute was set. */ bool has_modified_date() const { return Storage().isMember("modifiedDate"); } /** * Clears the '<code>modifiedDate</code>' attribute. */ void clear_modified_date() { MutableStorage()->removeMember("modifiedDate"); } /** * Get the value of the '<code>modifiedDate</code>' attribute. */ client::DateTime get_modified_date() const { const Json::Value& storage = Storage("modifiedDate"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>modifiedDate</code>' attribute. * * Last time this file was modified by anyone (formatted RFC 3339 timestamp). * This is only mutable on update when the setModifiedDate parameter is set. * * @param[in] value The new value. */ void set_modified_date(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("modifiedDate")); } /** * Determine if the '<code>openWithLinks</code>' attribute was set. * * @return true if the '<code>openWithLinks</code>' attribute was set. */ bool has_open_with_links() const { return Storage().isMember("openWithLinks"); } /** * Clears the '<code>openWithLinks</code>' attribute. */ void clear_open_with_links() { MutableStorage()->removeMember("openWithLinks"); } /** * Get a reference to the value of the '<code>openWithLinks</code>' attribute. */ const client::JsonCppAssociativeArray<string > get_open_with_links() const { const Json::Value& storage = Storage("openWithLinks"); return client::JsonValueToCppValueHelper<client::JsonCppAssociativeArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>openWithLinks</code>' * property. * * A map of the id of each of the user's apps to a link to open this file with * that app. Only populated when the drive.apps.readonly scope is used. * * @return The result can be modified to change the attribute value. */ client::JsonCppAssociativeArray<string > mutable_openWithLinks() { Json::Value* storage = MutableStorage("openWithLinks"); return client::JsonValueToMutableCppValueHelper<client::JsonCppAssociativeArray<string > >(storage); } /** * Determine if the '<code>originalFilename</code>' attribute was set. * * @return true if the '<code>originalFilename</code>' attribute was set. */ bool has_original_filename() const { return Storage().isMember("originalFilename"); } /** * Clears the '<code>originalFilename</code>' attribute. */ void clear_original_filename() { MutableStorage()->removeMember("originalFilename"); } /** * Get the value of the '<code>originalFilename</code>' attribute. */ const StringPiece get_original_filename() const { const Json::Value& v = Storage("originalFilename"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>originalFilename</code>' attribute. * * The original filename of the uploaded content if available, or else the * original value of the title field. This is only available for files with * binary content in Drive. * * @param[in] value The new value. */ void set_original_filename(const StringPiece& value) { *MutableStorage("originalFilename") = value.data(); } /** * Determine if the '<code>ownedByMe</code>' attribute was set. * * @return true if the '<code>ownedByMe</code>' attribute was set. */ bool has_owned_by_me() const { return Storage().isMember("ownedByMe"); } /** * Clears the '<code>ownedByMe</code>' attribute. */ void clear_owned_by_me() { MutableStorage()->removeMember("ownedByMe"); } /** * Get the value of the '<code>ownedByMe</code>' attribute. */ bool get_owned_by_me() const { const Json::Value& storage = Storage("ownedByMe"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>ownedByMe</code>' attribute. * * Whether the file is owned by the current user. Not populated for Team Drive * files. * * @param[in] value The new value. */ void set_owned_by_me(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("ownedByMe")); } /** * Determine if the '<code>ownerNames</code>' attribute was set. * * @return true if the '<code>ownerNames</code>' attribute was set. */ bool has_owner_names() const { return Storage().isMember("ownerNames"); } /** * Clears the '<code>ownerNames</code>' attribute. */ void clear_owner_names() { MutableStorage()->removeMember("ownerNames"); } /** * Get a reference to the value of the '<code>ownerNames</code>' attribute. */ const client::JsonCppArray<string > get_owner_names() const { const Json::Value& storage = Storage("ownerNames"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>ownerNames</code>' * property. * * Name(s) of the owner(s) of this file. Not populated for Team Drive files. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_ownerNames() { Json::Value* storage = MutableStorage("ownerNames"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>owners</code>' attribute was set. * * @return true if the '<code>owners</code>' attribute was set. */ bool has_owners() const { return Storage().isMember("owners"); } /** * Clears the '<code>owners</code>' attribute. */ void clear_owners() { MutableStorage()->removeMember("owners"); } /** * Get a reference to the value of the '<code>owners</code>' attribute. */ const client::JsonCppArray<User > get_owners() const; /** * Gets a reference to a mutable value of the '<code>owners</code>' property. * * The owner(s) of this file. Not populated for Team Drive files. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<User > mutable_owners(); /** * Determine if the '<code>parents</code>' attribute was set. * * @return true if the '<code>parents</code>' attribute was set. */ bool has_parents() const { return Storage().isMember("parents"); } /** * Clears the '<code>parents</code>' attribute. */ void clear_parents() { MutableStorage()->removeMember("parents"); } /** * Get a reference to the value of the '<code>parents</code>' attribute. */ const client::JsonCppArray<ParentReference > get_parents() const; /** * Gets a reference to a mutable value of the '<code>parents</code>' property. * * Collection of parent folders which contain this file. * Setting this field will put the file in all of the provided folders. On * insert, if no folders are provided, the file will be placed in the default * root folder. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<ParentReference > mutable_parents(); /** * Determine if the '<code>permissions</code>' attribute was set. * * @return true if the '<code>permissions</code>' attribute was set. */ bool has_permissions() const { return Storage().isMember("permissions"); } /** * Clears the '<code>permissions</code>' attribute. */ void clear_permissions() { MutableStorage()->removeMember("permissions"); } /** * Get a reference to the value of the '<code>permissions</code>' attribute. */ const client::JsonCppArray<Permission > get_permissions() const; /** * Gets a reference to a mutable value of the '<code>permissions</code>' * property. * * The list of permissions for users with access to this file. Not populated * for Team Drive files. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<Permission > mutable_permissions(); /** * Determine if the '<code>properties</code>' attribute was set. * * @return true if the '<code>properties</code>' attribute was set. */ bool has_properties() const { return Storage().isMember("properties"); } /** * Clears the '<code>properties</code>' attribute. */ void clear_properties() { MutableStorage()->removeMember("properties"); } /** * Get a reference to the value of the '<code>properties</code>' attribute. */ const client::JsonCppArray<Property > get_properties() const; /** * Gets a reference to a mutable value of the '<code>properties</code>' * property. * * The list of properties. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<Property > mutable_properties(); /** * Determine if the '<code>quotaBytesUsed</code>' attribute was set. * * @return true if the '<code>quotaBytesUsed</code>' attribute was set. */ bool has_quota_bytes_used() const { return Storage().isMember("quotaBytesUsed"); } /** * Clears the '<code>quotaBytesUsed</code>' attribute. */ void clear_quota_bytes_used() { MutableStorage()->removeMember("quotaBytesUsed"); } /** * Get the value of the '<code>quotaBytesUsed</code>' attribute. */ int64 get_quota_bytes_used() const { const Json::Value& storage = Storage("quotaBytesUsed"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>quotaBytesUsed</code>' attribute. * * The number of quota bytes used by this file. * * @param[in] value The new value. */ void set_quota_bytes_used(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("quotaBytesUsed")); } /** * Determine if the '<code>selfLink</code>' attribute was set. * * @return true if the '<code>selfLink</code>' attribute was set. */ bool has_self_link() const { return Storage().isMember("selfLink"); } /** * Clears the '<code>selfLink</code>' attribute. */ void clear_self_link() { MutableStorage()->removeMember("selfLink"); } /** * Get the value of the '<code>selfLink</code>' attribute. */ const StringPiece get_self_link() const { const Json::Value& v = Storage("selfLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>selfLink</code>' attribute. * * A link back to this file. * * @param[in] value The new value. */ void set_self_link(const StringPiece& value) { *MutableStorage("selfLink") = value.data(); } /** * Determine if the '<code>shareable</code>' attribute was set. * * @return true if the '<code>shareable</code>' attribute was set. */ bool has_shareable() const { return Storage().isMember("shareable"); } /** * Clears the '<code>shareable</code>' attribute. */ void clear_shareable() { MutableStorage()->removeMember("shareable"); } /** * Get the value of the '<code>shareable</code>' attribute. */ bool get_shareable() const { const Json::Value& storage = Storage("shareable"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>shareable</code>' attribute. * @deprecated * * * Deprecated: use capabilities/canShare. * * @param[in] value The new value. */ void set_shareable(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("shareable")); } /** * Determine if the '<code>shared</code>' attribute was set. * * @return true if the '<code>shared</code>' attribute was set. */ bool has_shared() const { return Storage().isMember("shared"); } /** * Clears the '<code>shared</code>' attribute. */ void clear_shared() { MutableStorage()->removeMember("shared"); } /** * Get the value of the '<code>shared</code>' attribute. */ bool get_shared() const { const Json::Value& storage = Storage("shared"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>shared</code>' attribute. * * Whether the file has been shared. Not populated for Team Drive files. * * @param[in] value The new value. */ void set_shared(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("shared")); } /** * Determine if the '<code>sharedWithMeDate</code>' attribute was set. * * @return true if the '<code>sharedWithMeDate</code>' attribute was set. */ bool has_shared_with_me_date() const { return Storage().isMember("sharedWithMeDate"); } /** * Clears the '<code>sharedWithMeDate</code>' attribute. */ void clear_shared_with_me_date() { MutableStorage()->removeMember("sharedWithMeDate"); } /** * Get the value of the '<code>sharedWithMeDate</code>' attribute. */ client::DateTime get_shared_with_me_date() const { const Json::Value& storage = Storage("sharedWithMeDate"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>sharedWithMeDate</code>' attribute. * * Time at which this file was shared with the user (formatted RFC 3339 * timestamp). * * @param[in] value The new value. */ void set_shared_with_me_date(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("sharedWithMeDate")); } /** * Determine if the '<code>sharingUser</code>' attribute was set. * * @return true if the '<code>sharingUser</code>' attribute was set. */ bool has_sharing_user() const { return Storage().isMember("sharingUser"); } /** * Clears the '<code>sharingUser</code>' attribute. */ void clear_sharing_user() { MutableStorage()->removeMember("sharingUser"); } /** * Get a reference to the value of the '<code>sharingUser</code>' attribute. */ const User get_sharing_user() const; /** * Gets a reference to a mutable value of the '<code>sharingUser</code>' * property. * * User that shared the item with the current user, if available. * * @return The result can be modified to change the attribute value. */ User mutable_sharingUser(); /** * Determine if the '<code>spaces</code>' attribute was set. * * @return true if the '<code>spaces</code>' attribute was set. */ bool has_spaces() const { return Storage().isMember("spaces"); } /** * Clears the '<code>spaces</code>' attribute. */ void clear_spaces() { MutableStorage()->removeMember("spaces"); } /** * Get a reference to the value of the '<code>spaces</code>' attribute. */ const client::JsonCppArray<string > get_spaces() const { const Json::Value& storage = Storage("spaces"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>spaces</code>' property. * * The list of spaces which contain the file. Supported values are 'drive', * 'appDataFolder' and 'photos'. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_spaces() { Json::Value* storage = MutableStorage("spaces"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>teamDriveId</code>' attribute was set. * * @return true if the '<code>teamDriveId</code>' attribute was set. */ bool has_team_drive_id() const { return Storage().isMember("teamDriveId"); } /** * Clears the '<code>teamDriveId</code>' attribute. */ void clear_team_drive_id() { MutableStorage()->removeMember("teamDriveId"); } /** * Get the value of the '<code>teamDriveId</code>' attribute. */ const StringPiece get_team_drive_id() const { const Json::Value& v = Storage("teamDriveId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>teamDriveId</code>' attribute. * * ID of the Team Drive the file resides in. * * @param[in] value The new value. */ void set_team_drive_id(const StringPiece& value) { *MutableStorage("teamDriveId") = value.data(); } /** * Determine if the '<code>thumbnail</code>' attribute was set. * * @return true if the '<code>thumbnail</code>' attribute was set. */ bool has_thumbnail() const { return Storage().isMember("thumbnail"); } /** * Clears the '<code>thumbnail</code>' attribute. */ void clear_thumbnail() { MutableStorage()->removeMember("thumbnail"); } /** * Get a reference to the value of the '<code>thumbnail</code>' attribute. */ const FileThumbnail get_thumbnail() const { const Json::Value& storage = Storage("thumbnail"); return client::JsonValueToCppValueHelper<FileThumbnail >(storage); } /** * Gets a reference to a mutable value of the '<code>thumbnail</code>' * property. * * A thumbnail for the file. This will only be used if Drive cannot generate a * standard thumbnail. * * @return The result can be modified to change the attribute value. */ FileThumbnail mutable_thumbnail() { Json::Value* storage = MutableStorage("thumbnail"); return client::JsonValueToMutableCppValueHelper<FileThumbnail >(storage); } /** * Determine if the '<code>thumbnailLink</code>' attribute was set. * * @return true if the '<code>thumbnailLink</code>' attribute was set. */ bool has_thumbnail_link() const { return Storage().isMember("thumbnailLink"); } /** * Clears the '<code>thumbnailLink</code>' attribute. */ void clear_thumbnail_link() { MutableStorage()->removeMember("thumbnailLink"); } /** * Get the value of the '<code>thumbnailLink</code>' attribute. */ const StringPiece get_thumbnail_link() const { const Json::Value& v = Storage("thumbnailLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>thumbnailLink</code>' attribute. * * A short-lived link to the file's thumbnail. Typically lasts on the order of * hours. Only populated when the requesting app can access the file's * content. * * @param[in] value The new value. */ void set_thumbnail_link(const StringPiece& value) { *MutableStorage("thumbnailLink") = value.data(); } /** * Determine if the '<code>thumbnailVersion</code>' attribute was set. * * @return true if the '<code>thumbnailVersion</code>' attribute was set. */ bool has_thumbnail_version() const { return Storage().isMember("thumbnailVersion"); } /** * Clears the '<code>thumbnailVersion</code>' attribute. */ void clear_thumbnail_version() { MutableStorage()->removeMember("thumbnailVersion"); } /** * Get the value of the '<code>thumbnailVersion</code>' attribute. */ int64 get_thumbnail_version() const { const Json::Value& storage = Storage("thumbnailVersion"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>thumbnailVersion</code>' attribute. * * The thumbnail version for use in thumbnail cache invalidation. * * @param[in] value The new value. */ void set_thumbnail_version(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("thumbnailVersion")); } /** * Determine if the '<code>title</code>' attribute was set. * * @return true if the '<code>title</code>' attribute was set. */ bool has_title() const { return Storage().isMember("title"); } /** * Clears the '<code>title</code>' attribute. */ void clear_title() { MutableStorage()->removeMember("title"); } /** * Get the value of the '<code>title</code>' attribute. */ const StringPiece get_title() const { const Json::Value& v = Storage("title"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>title</code>' attribute. * * The title of this file. Note that for immutable items such as the top level * folders of Team Drives, My Drive root folder, and Application Data folder * the title is constant. * * @param[in] value The new value. */ void set_title(const StringPiece& value) { *MutableStorage("title") = value.data(); } /** * Determine if the '<code>trashedDate</code>' attribute was set. * * @return true if the '<code>trashedDate</code>' attribute was set. */ bool has_trashed_date() const { return Storage().isMember("trashedDate"); } /** * Clears the '<code>trashedDate</code>' attribute. */ void clear_trashed_date() { MutableStorage()->removeMember("trashedDate"); } /** * Get the value of the '<code>trashedDate</code>' attribute. */ client::DateTime get_trashed_date() const { const Json::Value& storage = Storage("trashedDate"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>trashedDate</code>' attribute. * * The time that the item was trashed (formatted RFC 3339 timestamp). Only * populated for Team Drive files. * * @param[in] value The new value. */ void set_trashed_date(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("trashedDate")); } /** * Determine if the '<code>trashingUser</code>' attribute was set. * * @return true if the '<code>trashingUser</code>' attribute was set. */ bool has_trashing_user() const { return Storage().isMember("trashingUser"); } /** * Clears the '<code>trashingUser</code>' attribute. */ void clear_trashing_user() { MutableStorage()->removeMember("trashingUser"); } /** * Get a reference to the value of the '<code>trashingUser</code>' attribute. */ const User get_trashing_user() const; /** * Gets a reference to a mutable value of the '<code>trashingUser</code>' * property. * * If the file has been explicitly trashed, the user who trashed it. Only * populated for Team Drive files. * * @return The result can be modified to change the attribute value. */ User mutable_trashingUser(); /** * Determine if the '<code>userPermission</code>' attribute was set. * * @return true if the '<code>userPermission</code>' attribute was set. */ bool has_user_permission() const { return Storage().isMember("userPermission"); } /** * Clears the '<code>userPermission</code>' attribute. */ void clear_user_permission() { MutableStorage()->removeMember("userPermission"); } /** * Get a reference to the value of the '<code>userPermission</code>' * attribute. */ const Permission get_user_permission() const; /** * Gets a reference to a mutable value of the '<code>userPermission</code>' * property. * * The permissions for the authenticated user on this file. * * @return The result can be modified to change the attribute value. */ Permission mutable_userPermission(); /** * Determine if the '<code>version</code>' attribute was set. * * @return true if the '<code>version</code>' attribute was set. */ bool has_version() const { return Storage().isMember("version"); } /** * Clears the '<code>version</code>' attribute. */ void clear_version() { MutableStorage()->removeMember("version"); } /** * Get the value of the '<code>version</code>' attribute. */ int64 get_version() const { const Json::Value& storage = Storage("version"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>version</code>' attribute. * * A monotonically increasing version number for the file. This reflects every * change made to the file on the server, even those not visible to the * requesting user. * * @param[in] value The new value. */ void set_version(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("version")); } /** * Determine if the '<code>videoMediaMetadata</code>' attribute was set. * * @return true if the '<code>videoMediaMetadata</code>' attribute was set. */ bool has_video_media_metadata() const { return Storage().isMember("videoMediaMetadata"); } /** * Clears the '<code>videoMediaMetadata</code>' attribute. */ void clear_video_media_metadata() { MutableStorage()->removeMember("videoMediaMetadata"); } /** * Get a reference to the value of the '<code>videoMediaMetadata</code>' * attribute. */ const FileVideoMediaMetadata get_video_media_metadata() const { const Json::Value& storage = Storage("videoMediaMetadata"); return client::JsonValueToCppValueHelper<FileVideoMediaMetadata >(storage); } /** * Gets a reference to a mutable value of the * '<code>videoMediaMetadata</code>' property. * * Metadata about video media. This will only be present for video types. * * @return The result can be modified to change the attribute value. */ FileVideoMediaMetadata mutable_videoMediaMetadata() { Json::Value* storage = MutableStorage("videoMediaMetadata"); return client::JsonValueToMutableCppValueHelper<FileVideoMediaMetadata >(storage); } /** * Determine if the '<code>webContentLink</code>' attribute was set. * * @return true if the '<code>webContentLink</code>' attribute was set. */ bool has_web_content_link() const { return Storage().isMember("webContentLink"); } /** * Clears the '<code>webContentLink</code>' attribute. */ void clear_web_content_link() { MutableStorage()->removeMember("webContentLink"); } /** * Get the value of the '<code>webContentLink</code>' attribute. */ const StringPiece get_web_content_link() const { const Json::Value& v = Storage("webContentLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>webContentLink</code>' attribute. * * A link for downloading the content of the file in a browser using cookie * based authentication. In cases where the content is shared publicly, the * content can be downloaded without any credentials. * * @param[in] value The new value. */ void set_web_content_link(const StringPiece& value) { *MutableStorage("webContentLink") = value.data(); } /** * Determine if the '<code>webViewLink</code>' attribute was set. * * @return true if the '<code>webViewLink</code>' attribute was set. */ bool has_web_view_link() const { return Storage().isMember("webViewLink"); } /** * Clears the '<code>webViewLink</code>' attribute. */ void clear_web_view_link() { MutableStorage()->removeMember("webViewLink"); } /** * Get the value of the '<code>webViewLink</code>' attribute. */ const StringPiece get_web_view_link() const { const Json::Value& v = Storage("webViewLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>webViewLink</code>' attribute. * * A link only available on public folders for viewing their static web assets * (HTML, CSS, JS, etc) via Google Drive's Website Hosting. * * @param[in] value The new value. */ void set_web_view_link(const StringPiece& value) { *MutableStorage("webViewLink") = value.data(); } /** * Determine if the '<code>writersCanShare</code>' attribute was set. * * @return true if the '<code>writersCanShare</code>' attribute was set. */ bool has_writers_can_share() const { return Storage().isMember("writersCanShare"); } /** * Clears the '<code>writersCanShare</code>' attribute. */ void clear_writers_can_share() { MutableStorage()->removeMember("writersCanShare"); } /** * Get the value of the '<code>writersCanShare</code>' attribute. */ bool get_writers_can_share() const { const Json::Value& storage = Storage("writersCanShare"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>writersCanShare</code>' attribute. * * Whether writers can share the document with other users. Not populated for * Team Drive files. * * @param[in] value The new value. */ void set_writers_can_share(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("writersCanShare")); } private: void operator=(const File&); }; // File } // namespace google_drive_api #endif // GOOGLE_DRIVE_API_FILE_H_ <file_sep>/service_apis/youtube/google/youtube_api/invideo_timing.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_INVIDEO_TIMING_H_ #define GOOGLE_YOUTUBE_API_INVIDEO_TIMING_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Describes a temporal position of a visual widget inside a video. * * @ingroup DataObject */ class InvideoTiming : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static InvideoTiming* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit InvideoTiming(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit InvideoTiming(Json::Value* storage); /** * Standard destructor. */ virtual ~InvideoTiming(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::InvideoTiming</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::InvideoTiming"); } /** * Determine if the '<code>durationMs</code>' attribute was set. * * @return true if the '<code>durationMs</code>' attribute was set. */ bool has_duration_ms() const { return Storage().isMember("durationMs"); } /** * Clears the '<code>durationMs</code>' attribute. */ void clear_duration_ms() { MutableStorage()->removeMember("durationMs"); } /** * Get the value of the '<code>durationMs</code>' attribute. */ uint64 get_duration_ms() const { const Json::Value& storage = Storage("durationMs"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>durationMs</code>' attribute. * * Defines the duration in milliseconds for which the promotion should be * displayed. If missing, the client should use the default. * * @param[in] value The new value. */ void set_duration_ms(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("durationMs")); } /** * Determine if the '<code>offsetMs</code>' attribute was set. * * @return true if the '<code>offsetMs</code>' attribute was set. */ bool has_offset_ms() const { return Storage().isMember("offsetMs"); } /** * Clears the '<code>offsetMs</code>' attribute. */ void clear_offset_ms() { MutableStorage()->removeMember("offsetMs"); } /** * Get the value of the '<code>offsetMs</code>' attribute. */ uint64 get_offset_ms() const { const Json::Value& storage = Storage("offsetMs"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>offsetMs</code>' attribute. * * Defines the time at which the promotion will appear. Depending on the value * of type the value of the offsetMs field will represent a time offset from * the start or from the end of the video, expressed in milliseconds. * * @param[in] value The new value. */ void set_offset_ms(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("offsetMs")); } /** * Determine if the '<code>type</code>' attribute was set. * * @return true if the '<code>type</code>' attribute was set. */ bool has_type() const { return Storage().isMember("type"); } /** * Clears the '<code>type</code>' attribute. */ void clear_type() { MutableStorage()->removeMember("type"); } /** * Get the value of the '<code>type</code>' attribute. */ const StringPiece get_type() const { const Json::Value& v = Storage("type"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>type</code>' attribute. * * Describes a timing type. If the value is offsetFromStart, then the offsetMs * field represents an offset from the start of the video. If the value is * offsetFromEnd, then the offsetMs field represents an offset from the end of * the video. * * @param[in] value The new value. */ void set_type(const StringPiece& value) { *MutableStorage("type") = value.data(); } private: void operator=(const InvideoTiming&); }; // InvideoTiming } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_INVIDEO_TIMING_H_ <file_sep>/service_apis/drive/google/drive_api/change.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Drive API (drive/v2) // Generated from: // Version: v2 // Revision: 20170512 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_DRIVE_API_CHANGE_H_ #define GOOGLE_DRIVE_API_CHANGE_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/drive_api/file.h" #include "google/drive_api/team_drive.h" namespace Json { class Value; } // namespace Json namespace google_drive_api { using namespace googleapis; /** * Representation of a change to a file or Team Drive. * * @ingroup DataObject */ class Change : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static Change* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Change(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Change(Json::Value* storage); /** * Standard destructor. */ virtual ~Change(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::Change</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::Change"); } /** * Determine if the '<code>deleted</code>' attribute was set. * * @return true if the '<code>deleted</code>' attribute was set. */ bool has_deleted() const { return Storage().isMember("deleted"); } /** * Clears the '<code>deleted</code>' attribute. */ void clear_deleted() { MutableStorage()->removeMember("deleted"); } /** * Get the value of the '<code>deleted</code>' attribute. */ bool get_deleted() const { const Json::Value& storage = Storage("deleted"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>deleted</code>' attribute. * * Whether the file or Team Drive has been removed from this list of changes, * for example by deletion or loss of access. * * @param[in] value The new value. */ void set_deleted(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("deleted")); } /** * Determine if the '<code>file</code>' attribute was set. * * @return true if the '<code>file</code>' attribute was set. */ bool has_file() const { return Storage().isMember("file"); } /** * Clears the '<code>file</code>' attribute. */ void clear_file() { MutableStorage()->removeMember("file"); } /** * Get a reference to the value of the '<code>file</code>' attribute. */ const File get_file() const; /** * Gets a reference to a mutable value of the '<code>file</code>' property. * * The updated state of the file. Present if the type is file and the file has * not been removed from this list of changes. * * @return The result can be modified to change the attribute value. */ File mutable_file(); /** * Determine if the '<code>fileId</code>' attribute was set. * * @return true if the '<code>fileId</code>' attribute was set. */ bool has_file_id() const { return Storage().isMember("fileId"); } /** * Clears the '<code>fileId</code>' attribute. */ void clear_file_id() { MutableStorage()->removeMember("fileId"); } /** * Get the value of the '<code>fileId</code>' attribute. */ const StringPiece get_file_id() const { const Json::Value& v = Storage("fileId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>fileId</code>' attribute. * * The ID of the file associated with this change. * * @param[in] value The new value. */ void set_file_id(const StringPiece& value) { *MutableStorage("fileId") = value.data(); } /** * Determine if the '<code>id</code>' attribute was set. * * @return true if the '<code>id</code>' attribute was set. */ bool has_id() const { return Storage().isMember("id"); } /** * Clears the '<code>id</code>' attribute. */ void clear_id() { MutableStorage()->removeMember("id"); } /** * Get the value of the '<code>id</code>' attribute. */ int64 get_id() const { const Json::Value& storage = Storage("id"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>id</code>' attribute. * * The ID of the change. * * @param[in] value The new value. */ void set_id(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("id")); } /** * Determine if the '<code>kind</code>' attribute was set. * * @return true if the '<code>kind</code>' attribute was set. */ bool has_kind() const { return Storage().isMember("kind"); } /** * Clears the '<code>kind</code>' attribute. */ void clear_kind() { MutableStorage()->removeMember("kind"); } /** * Get the value of the '<code>kind</code>' attribute. */ const StringPiece get_kind() const { const Json::Value& v = Storage("kind"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kind</code>' attribute. * * This is always drive#change. * * @param[in] value The new value. */ void set_kind(const StringPiece& value) { *MutableStorage("kind") = value.data(); } /** * Determine if the '<code>modificationDate</code>' attribute was set. * * @return true if the '<code>modificationDate</code>' attribute was set. */ bool has_modification_date() const { return Storage().isMember("modificationDate"); } /** * Clears the '<code>modificationDate</code>' attribute. */ void clear_modification_date() { MutableStorage()->removeMember("modificationDate"); } /** * Get the value of the '<code>modificationDate</code>' attribute. */ client::DateTime get_modification_date() const { const Json::Value& storage = Storage("modificationDate"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>modificationDate</code>' attribute. * * The time of this modification. * * @param[in] value The new value. */ void set_modification_date(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("modificationDate")); } /** * Determine if the '<code>selfLink</code>' attribute was set. * * @return true if the '<code>selfLink</code>' attribute was set. */ bool has_self_link() const { return Storage().isMember("selfLink"); } /** * Clears the '<code>selfLink</code>' attribute. */ void clear_self_link() { MutableStorage()->removeMember("selfLink"); } /** * Get the value of the '<code>selfLink</code>' attribute. */ const StringPiece get_self_link() const { const Json::Value& v = Storage("selfLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>selfLink</code>' attribute. * * A link back to this change. * * @param[in] value The new value. */ void set_self_link(const StringPiece& value) { *MutableStorage("selfLink") = value.data(); } /** * Determine if the '<code>teamDrive</code>' attribute was set. * * @return true if the '<code>teamDrive</code>' attribute was set. */ bool has_team_drive() const { return Storage().isMember("teamDrive"); } /** * Clears the '<code>teamDrive</code>' attribute. */ void clear_team_drive() { MutableStorage()->removeMember("teamDrive"); } /** * Get a reference to the value of the '<code>teamDrive</code>' attribute. */ const TeamDrive get_team_drive() const; /** * Gets a reference to a mutable value of the '<code>teamDrive</code>' * property. * * The updated state of the Team Drive. Present if the type is teamDrive, the * user is still a member of the Team Drive, and the Team Drive has not been * deleted. * * @return The result can be modified to change the attribute value. */ TeamDrive mutable_teamDrive(); /** * Determine if the '<code>teamDriveId</code>' attribute was set. * * @return true if the '<code>teamDriveId</code>' attribute was set. */ bool has_team_drive_id() const { return Storage().isMember("teamDriveId"); } /** * Clears the '<code>teamDriveId</code>' attribute. */ void clear_team_drive_id() { MutableStorage()->removeMember("teamDriveId"); } /** * Get the value of the '<code>teamDriveId</code>' attribute. */ const StringPiece get_team_drive_id() const { const Json::Value& v = Storage("teamDriveId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>teamDriveId</code>' attribute. * * The ID of the Team Drive associated with this change. * * @param[in] value The new value. */ void set_team_drive_id(const StringPiece& value) { *MutableStorage("teamDriveId") = value.data(); } /** * Determine if the '<code>type</code>' attribute was set. * * @return true if the '<code>type</code>' attribute was set. */ bool has_type() const { return Storage().isMember("type"); } /** * Clears the '<code>type</code>' attribute. */ void clear_type() { MutableStorage()->removeMember("type"); } /** * Get the value of the '<code>type</code>' attribute. */ const StringPiece get_type() const { const Json::Value& v = Storage("type"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>type</code>' attribute. * * The type of the change. Possible values are file and teamDrive. * * @param[in] value The new value. */ void set_type(const StringPiece& value) { *MutableStorage("type") = value.data(); } private: void operator=(const Change&); }; // Change } // namespace google_drive_api #endif // GOOGLE_DRIVE_API_CHANGE_H_ <file_sep>/service_apis/youtube/google/youtube_api/monitor_stream_info.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_MONITOR_STREAM_INFO_H_ #define GOOGLE_YOUTUBE_API_MONITOR_STREAM_INFO_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Settings and Info of the monitor stream. * * @ingroup DataObject */ class MonitorStreamInfo : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static MonitorStreamInfo* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit MonitorStreamInfo(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit MonitorStreamInfo(Json::Value* storage); /** * Standard destructor. */ virtual ~MonitorStreamInfo(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::MonitorStreamInfo</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::MonitorStreamInfo"); } /** * Determine if the '<code>broadcastStreamDelayMs</code>' attribute was set. * * @return true if the '<code>broadcastStreamDelayMs</code>' attribute was * set. */ bool has_broadcast_stream_delay_ms() const { return Storage().isMember("broadcastStreamDelayMs"); } /** * Clears the '<code>broadcastStreamDelayMs</code>' attribute. */ void clear_broadcast_stream_delay_ms() { MutableStorage()->removeMember("broadcastStreamDelayMs"); } /** * Get the value of the '<code>broadcastStreamDelayMs</code>' attribute. */ uint32 get_broadcast_stream_delay_ms() const { const Json::Value& storage = Storage("broadcastStreamDelayMs"); return client::JsonValueToCppValueHelper<uint32 >(storage); } /** * Change the '<code>broadcastStreamDelayMs</code>' attribute. * * If you have set the enableMonitorStream property to true, then this * property determines the length of the live broadcast delay. * * @param[in] value The new value. */ void set_broadcast_stream_delay_ms(uint32 value) { client::SetJsonValueFromCppValueHelper<uint32 >( value, MutableStorage("broadcastStreamDelayMs")); } /** * Determine if the '<code>embedHtml</code>' attribute was set. * * @return true if the '<code>embedHtml</code>' attribute was set. */ bool has_embed_html() const { return Storage().isMember("embedHtml"); } /** * Clears the '<code>embedHtml</code>' attribute. */ void clear_embed_html() { MutableStorage()->removeMember("embedHtml"); } /** * Get the value of the '<code>embedHtml</code>' attribute. */ const StringPiece get_embed_html() const { const Json::Value& v = Storage("embedHtml"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>embedHtml</code>' attribute. * * HTML code that embeds a player that plays the monitor stream. * * @param[in] value The new value. */ void set_embed_html(const StringPiece& value) { *MutableStorage("embedHtml") = value.data(); } /** * Determine if the '<code>enableMonitorStream</code>' attribute was set. * * @return true if the '<code>enableMonitorStream</code>' attribute was set. */ bool has_enable_monitor_stream() const { return Storage().isMember("enableMonitorStream"); } /** * Clears the '<code>enableMonitorStream</code>' attribute. */ void clear_enable_monitor_stream() { MutableStorage()->removeMember("enableMonitorStream"); } /** * Get the value of the '<code>enableMonitorStream</code>' attribute. */ bool get_enable_monitor_stream() const { const Json::Value& storage = Storage("enableMonitorStream"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>enableMonitorStream</code>' attribute. * * This value determines whether the monitor stream is enabled for the * broadcast. If the monitor stream is enabled, then YouTube will broadcast * the event content on a special stream intended only for the broadcaster's * consumption. The broadcaster can use the stream to review the event content * and also to identify the optimal times to insert cuepoints. * * You need to set this value to true if you intend to have a broadcast delay * for your event. * * Note: This property cannot be updated once the broadcast is in the testing * or live state. * * @param[in] value The new value. */ void set_enable_monitor_stream(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("enableMonitorStream")); } private: void operator=(const MonitorStreamInfo&); }; // MonitorStreamInfo } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_MONITOR_STREAM_INFO_H_ <file_sep>/service_apis/youtube/google/youtube_api/video_live_streaming_details.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_VIDEO_LIVE_STREAMING_DETAILS_H_ #define GOOGLE_YOUTUBE_API_VIDEO_LIVE_STREAMING_DETAILS_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Details about the live streaming metadata. * * @ingroup DataObject */ class VideoLiveStreamingDetails : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static VideoLiveStreamingDetails* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoLiveStreamingDetails(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoLiveStreamingDetails(Json::Value* storage); /** * Standard destructor. */ virtual ~VideoLiveStreamingDetails(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::VideoLiveStreamingDetails</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::VideoLiveStreamingDetails"); } /** * Determine if the '<code>activeLiveChatId</code>' attribute was set. * * @return true if the '<code>activeLiveChatId</code>' attribute was set. */ bool has_active_live_chat_id() const { return Storage().isMember("activeLiveChatId"); } /** * Clears the '<code>activeLiveChatId</code>' attribute. */ void clear_active_live_chat_id() { MutableStorage()->removeMember("activeLiveChatId"); } /** * Get the value of the '<code>activeLiveChatId</code>' attribute. */ const StringPiece get_active_live_chat_id() const { const Json::Value& v = Storage("activeLiveChatId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>activeLiveChatId</code>' attribute. * * The ID of the currently active live chat attached to this video. This field * is filled only if the video is a currently live broadcast that has live * chat. Once the broadcast transitions to complete this field will be removed * and the live chat closed down. For persistent broadcasts that live chat id * will no longer be tied to this video but rather to the new video being * displayed at the persistent page. * * @param[in] value The new value. */ void set_active_live_chat_id(const StringPiece& value) { *MutableStorage("activeLiveChatId") = value.data(); } /** * Determine if the '<code>actualEndTime</code>' attribute was set. * * @return true if the '<code>actualEndTime</code>' attribute was set. */ bool has_actual_end_time() const { return Storage().isMember("actualEndTime"); } /** * Clears the '<code>actualEndTime</code>' attribute. */ void clear_actual_end_time() { MutableStorage()->removeMember("actualEndTime"); } /** * Get the value of the '<code>actualEndTime</code>' attribute. */ client::DateTime get_actual_end_time() const { const Json::Value& storage = Storage("actualEndTime"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>actualEndTime</code>' attribute. * * The time that the broadcast actually ended. The value is specified in ISO * 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. This value will not be available * until the broadcast is over. * * @param[in] value The new value. */ void set_actual_end_time(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("actualEndTime")); } /** * Determine if the '<code>actualStartTime</code>' attribute was set. * * @return true if the '<code>actualStartTime</code>' attribute was set. */ bool has_actual_start_time() const { return Storage().isMember("actualStartTime"); } /** * Clears the '<code>actualStartTime</code>' attribute. */ void clear_actual_start_time() { MutableStorage()->removeMember("actualStartTime"); } /** * Get the value of the '<code>actualStartTime</code>' attribute. */ client::DateTime get_actual_start_time() const { const Json::Value& storage = Storage("actualStartTime"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>actualStartTime</code>' attribute. * * The time that the broadcast actually started. The value is specified in ISO * 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. This value will not be available * until the broadcast begins. * * @param[in] value The new value. */ void set_actual_start_time(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("actualStartTime")); } /** * Determine if the '<code>concurrentViewers</code>' attribute was set. * * @return true if the '<code>concurrentViewers</code>' attribute was set. */ bool has_concurrent_viewers() const { return Storage().isMember("concurrentViewers"); } /** * Clears the '<code>concurrentViewers</code>' attribute. */ void clear_concurrent_viewers() { MutableStorage()->removeMember("concurrentViewers"); } /** * Get the value of the '<code>concurrentViewers</code>' attribute. */ uint64 get_concurrent_viewers() const { const Json::Value& storage = Storage("concurrentViewers"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>concurrentViewers</code>' attribute. * * The number of viewers currently watching the broadcast. The property and * its value will be present if the broadcast has current viewers and the * broadcast owner has not hidden the viewcount for the video. Note that * YouTube stops tracking the number of concurrent viewers for a broadcast * when the broadcast ends. So, this property would not identify the number of * viewers watching an archived video of a live broadcast that already ended. * * @param[in] value The new value. */ void set_concurrent_viewers(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("concurrentViewers")); } /** * Determine if the '<code>scheduledEndTime</code>' attribute was set. * * @return true if the '<code>scheduledEndTime</code>' attribute was set. */ bool has_scheduled_end_time() const { return Storage().isMember("scheduledEndTime"); } /** * Clears the '<code>scheduledEndTime</code>' attribute. */ void clear_scheduled_end_time() { MutableStorage()->removeMember("scheduledEndTime"); } /** * Get the value of the '<code>scheduledEndTime</code>' attribute. */ client::DateTime get_scheduled_end_time() const { const Json::Value& storage = Storage("scheduledEndTime"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>scheduledEndTime</code>' attribute. * * The time that the broadcast is scheduled to end. The value is specified in * ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. If the value is empty or the * property is not present, then the broadcast is scheduled to continue * indefinitely. * * @param[in] value The new value. */ void set_scheduled_end_time(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("scheduledEndTime")); } /** * Determine if the '<code>scheduledStartTime</code>' attribute was set. * * @return true if the '<code>scheduledStartTime</code>' attribute was set. */ bool has_scheduled_start_time() const { return Storage().isMember("scheduledStartTime"); } /** * Clears the '<code>scheduledStartTime</code>' attribute. */ void clear_scheduled_start_time() { MutableStorage()->removeMember("scheduledStartTime"); } /** * Get the value of the '<code>scheduledStartTime</code>' attribute. */ client::DateTime get_scheduled_start_time() const { const Json::Value& storage = Storage("scheduledStartTime"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>scheduledStartTime</code>' attribute. * * The time that the broadcast is scheduled to begin. The value is specified * in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. * * @param[in] value The new value. */ void set_scheduled_start_time(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("scheduledStartTime")); } private: void operator=(const VideoLiveStreamingDetails&); }; // VideoLiveStreamingDetails } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_VIDEO_LIVE_STREAMING_DETAILS_H_ <file_sep>/service_apis/youtube/google/youtube_api/youtube_api.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 #ifndef GOOGLE_YOUTUBE_API_YOUTUBE_API_H_ #define GOOGLE_YOUTUBE_API_YOUTUBE_API_H_ #include "google/youtube_api/access_policy.h" #include "google/youtube_api/resource_id.h" #include "google/youtube_api/activity_content_details_bulletin.h" #include "google/youtube_api/activity_content_details_channel_item.h" #include "google/youtube_api/activity_content_details_comment.h" #include "google/youtube_api/activity_content_details_favorite.h" #include "google/youtube_api/activity_content_details_like.h" #include "google/youtube_api/activity_content_details_playlist_item.h" #include "google/youtube_api/activity_content_details_promoted_item.h" #include "google/youtube_api/activity_content_details_recommendation.h" #include "google/youtube_api/activity_content_details_social.h" #include "google/youtube_api/activity_content_details_subscription.h" #include "google/youtube_api/activity_content_details_upload.h" #include "google/youtube_api/activity_content_details.h" #include "google/youtube_api/thumbnail.h" #include "google/youtube_api/thumbnail_details.h" #include "google/youtube_api/activity_snippet.h" #include "google/youtube_api/activity.h" #include "google/youtube_api/page_info.h" #include "google/youtube_api/token_pagination.h" #include "google/youtube_api/activity_list_response.h" #include "google/youtube_api/caption_snippet.h" #include "google/youtube_api/caption.h" #include "google/youtube_api/caption_list_response.h" #include "google/youtube_api/ingestion_info.h" #include "google/youtube_api/cdn_settings.h" #include "google/youtube_api/channel_audit_details.h" #include "google/youtube_api/channel_settings.h" #include "google/youtube_api/property_value.h" #include "google/youtube_api/language_tag.h" #include "google/youtube_api/localized_string.h" #include "google/youtube_api/localized_property.h" #include "google/youtube_api/image_settings.h" #include "google/youtube_api/watch_settings.h" #include "google/youtube_api/channel_branding_settings.h" #include "google/youtube_api/channel_content_details.h" #include "google/youtube_api/channel_content_owner_details.h" #include "google/youtube_api/channel_conversion_ping.h" #include "google/youtube_api/channel_conversion_pings.h" #include "google/youtube_api/invideo_timing.h" #include "google/youtube_api/promoted_item_id.h" #include "google/youtube_api/promoted_item.h" #include "google/youtube_api/invideo_position.h" #include "google/youtube_api/invideo_promotion.h" #include "google/youtube_api/channel_localization.h" #include "google/youtube_api/channel_snippet.h" #include "google/youtube_api/channel_statistics.h" #include "google/youtube_api/channel_status.h" #include "google/youtube_api/channel_topic_details.h" #include "google/youtube_api/channel.h" #include "google/youtube_api/channel_banner_resource.h" #include "google/youtube_api/channel_list_response.h" #include "google/youtube_api/channel_profile_details.h" #include "google/youtube_api/channel_section_content_details.h" #include "google/youtube_api/channel_section_localization.h" #include "google/youtube_api/channel_section_snippet.h" #include "google/youtube_api/channel_section_targeting.h" #include "google/youtube_api/channel_section.h" #include "google/youtube_api/channel_section_list_response.h" #include "google/youtube_api/comment_snippet.h" #include "google/youtube_api/comment.h" #include "google/youtube_api/comment_list_response.h" #include "google/youtube_api/comment_thread_replies.h" #include "google/youtube_api/comment_thread_snippet.h" #include "google/youtube_api/comment_thread.h" #include "google/youtube_api/comment_thread_list_response.h" #include "google/youtube_api/content_rating.h" #include "google/youtube_api/fan_funding_event_snippet.h" #include "google/youtube_api/fan_funding_event.h" #include "google/youtube_api/fan_funding_event_list_response.h" #include "google/youtube_api/geo_point.h" #include "google/youtube_api/guide_category_snippet.h" #include "google/youtube_api/guide_category.h" #include "google/youtube_api/guide_category_list_response.h" #include "google/youtube_api/i18n_language_snippet.h" #include "google/youtube_api/i18n_language.h" #include "google/youtube_api/i18n_language_list_response.h" #include "google/youtube_api/i18n_region_snippet.h" #include "google/youtube_api/i18n_region.h" #include "google/youtube_api/i18n_region_list_response.h" #include "google/youtube_api/invideo_branding.h" #include "google/youtube_api/monitor_stream_info.h" #include "google/youtube_api/live_broadcast_content_details.h" #include "google/youtube_api/live_broadcast_snippet.h" #include "google/youtube_api/live_broadcast_statistics.h" #include "google/youtube_api/live_broadcast_status.h" #include "google/youtube_api/live_broadcast_topic_snippet.h" #include "google/youtube_api/live_broadcast_topic.h" #include "google/youtube_api/live_broadcast_topic_details.h" #include "google/youtube_api/live_broadcast.h" #include "google/youtube_api/live_broadcast_list_response.h" #include "google/youtube_api/live_chat_ban_snippet.h" #include "google/youtube_api/live_chat_ban.h" #include "google/youtube_api/live_chat_fan_funding_event_details.h" #include "google/youtube_api/live_chat_message_author_details.h" #include "google/youtube_api/live_chat_message_deleted_details.h" #include "google/youtube_api/live_chat_message_retracted_details.h" #include "google/youtube_api/live_chat_poll_closed_details.h" #include "google/youtube_api/live_chat_poll_item.h" #include "google/youtube_api/live_chat_poll_edited_details.h" #include "google/youtube_api/live_chat_poll_opened_details.h" #include "google/youtube_api/live_chat_poll_voted_details.h" #include "google/youtube_api/live_chat_super_chat_details.h" #include "google/youtube_api/live_chat_text_message_details.h" #include "google/youtube_api/live_chat_user_banned_message_details.h" #include "google/youtube_api/live_chat_message_snippet.h" #include "google/youtube_api/live_chat_message.h" #include "google/youtube_api/live_chat_message_list_response.h" #include "google/youtube_api/live_chat_moderator_snippet.h" #include "google/youtube_api/live_chat_moderator.h" #include "google/youtube_api/live_chat_moderator_list_response.h" #include "google/youtube_api/live_stream_content_details.h" #include "google/youtube_api/live_stream_snippet.h" #include "google/youtube_api/live_stream_configuration_issue.h" #include "google/youtube_api/live_stream_health_status.h" #include "google/youtube_api/live_stream_status.h" #include "google/youtube_api/live_stream.h" #include "google/youtube_api/live_stream_list_response.h" #include "google/youtube_api/playlist_content_details.h" #include "google/youtube_api/playlist_localization.h" #include "google/youtube_api/playlist_player.h" #include "google/youtube_api/playlist_snippet.h" #include "google/youtube_api/playlist_status.h" #include "google/youtube_api/playlist.h" #include "google/youtube_api/playlist_item_content_details.h" #include "google/youtube_api/playlist_item_snippet.h" #include "google/youtube_api/playlist_item_status.h" #include "google/youtube_api/playlist_item.h" #include "google/youtube_api/playlist_item_list_response.h" #include "google/youtube_api/playlist_list_response.h" #include "google/youtube_api/search_result_snippet.h" #include "google/youtube_api/search_result.h" #include "google/youtube_api/search_list_response.h" #include "google/youtube_api/sponsor_snippet.h" #include "google/youtube_api/sponsor.h" #include "google/youtube_api/sponsor_list_response.h" #include "google/youtube_api/subscription_content_details.h" #include "google/youtube_api/subscription_snippet.h" #include "google/youtube_api/subscription_subscriber_snippet.h" #include "google/youtube_api/subscription.h" #include "google/youtube_api/subscription_list_response.h" #include "google/youtube_api/super_chat_event_snippet.h" #include "google/youtube_api/super_chat_event.h" #include "google/youtube_api/super_chat_event_list_response.h" #include "google/youtube_api/thumbnail_set_response.h" #include "google/youtube_api/video_age_gating.h" #include "google/youtube_api/video_content_details_region_restriction.h" #include "google/youtube_api/video_content_details.h" #include "google/youtube_api/video_file_details_audio_stream.h" #include "google/youtube_api/video_file_details_video_stream.h" #include "google/youtube_api/video_file_details.h" #include "google/youtube_api/video_live_streaming_details.h" #include "google/youtube_api/video_localization.h" #include "google/youtube_api/video_monetization_details.h" #include "google/youtube_api/video_player.h" #include "google/youtube_api/video_processing_details_processing_progress.h" #include "google/youtube_api/video_processing_details.h" #include "google/youtube_api/video_project_details.h" #include "google/youtube_api/video_recording_details.h" #include "google/youtube_api/video_snippet.h" #include "google/youtube_api/video_statistics.h" #include "google/youtube_api/video_status.h" #include "google/youtube_api/video_suggestions_tag_suggestion.h" #include "google/youtube_api/video_suggestions.h" #include "google/youtube_api/video_topic_details.h" #include "google/youtube_api/video.h" #include "google/youtube_api/video_abuse_report.h" #include "google/youtube_api/video_abuse_report_secondary_reason.h" #include "google/youtube_api/video_abuse_report_reason_snippet.h" #include "google/youtube_api/video_abuse_report_reason.h" #include "google/youtube_api/video_abuse_report_reason_list_response.h" #include "google/youtube_api/video_category_snippet.h" #include "google/youtube_api/video_category.h" #include "google/youtube_api/video_category_list_response.h" #include "google/youtube_api/video_rating.h" #include "google/youtube_api/video_get_rating_response.h" #include "google/youtube_api/video_list_response.h" #include "google/youtube_api/you_tube_service.h" #endif // GOOGLE_YOUTUBE_API_YOUTUBE_API_H_ <file_sep>/service_apis/youtube/google/youtube_api/invideo_promotion.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Description: // Supports core YouTube features, such as uploading videos, creating and managing playlists, searching for content, and much more. // Classes: // InvideoPromotion // Documentation: // https://developers.google.com/youtube/v3 #include "google/youtube_api/invideo_promotion.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/invideo_position.h" #include "google/youtube_api/invideo_timing.h" #include "google/youtube_api/promoted_item.h" #include <string> #include "googleapis/strings/strcat.h" namespace google_youtube_api { using namespace googleapis; // Object factory method (static). InvideoPromotion* InvideoPromotion::New() { return new client::JsonCppCapsule<InvideoPromotion>; } // Standard immutable constructor. InvideoPromotion::InvideoPromotion(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. InvideoPromotion::InvideoPromotion(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. InvideoPromotion::~InvideoPromotion() { } // Properties. const InvideoTiming InvideoPromotion::get_default_timing() const { const Json::Value& storage = Storage("defaultTiming"); return client::JsonValueToCppValueHelper<InvideoTiming >(storage); } InvideoTiming InvideoPromotion::mutable_defaultTiming() { Json::Value* storage = MutableStorage("defaultTiming"); return client::JsonValueToMutableCppValueHelper<InvideoTiming >(storage); } const client::JsonCppArray<PromotedItem > InvideoPromotion::get_items() const { const Json::Value& storage = Storage("items"); return client::JsonValueToCppValueHelper<client::JsonCppArray<PromotedItem > >(storage); } client::JsonCppArray<PromotedItem > InvideoPromotion::mutable_items() { Json::Value* storage = MutableStorage("items"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<PromotedItem > >(storage); } const InvideoPosition InvideoPromotion::get_position() const { const Json::Value& storage = Storage("position"); return client::JsonValueToCppValueHelper<InvideoPosition >(storage); } InvideoPosition InvideoPromotion::mutable_position() { Json::Value* storage = MutableStorage("position"); return client::JsonValueToMutableCppValueHelper<InvideoPosition >(storage); } } // namespace google_youtube_api <file_sep>/service_apis/youtube/google/youtube_api/live_broadcast_statistics.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_LIVE_BROADCAST_STATISTICS_H_ #define GOOGLE_YOUTUBE_API_LIVE_BROADCAST_STATISTICS_H_ #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Statistics about the live broadcast. These represent a snapshot of the values * at the time of the request. Statistics are only returned for live broadcasts. * * @ingroup DataObject */ class LiveBroadcastStatistics : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static LiveBroadcastStatistics* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveBroadcastStatistics(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveBroadcastStatistics(Json::Value* storage); /** * Standard destructor. */ virtual ~LiveBroadcastStatistics(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::LiveBroadcastStatistics</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::LiveBroadcastStatistics"); } /** * Determine if the '<code>concurrentViewers</code>' attribute was set. * * @return true if the '<code>concurrentViewers</code>' attribute was set. */ bool has_concurrent_viewers() const { return Storage().isMember("concurrentViewers"); } /** * Clears the '<code>concurrentViewers</code>' attribute. */ void clear_concurrent_viewers() { MutableStorage()->removeMember("concurrentViewers"); } /** * Get the value of the '<code>concurrentViewers</code>' attribute. */ uint64 get_concurrent_viewers() const { const Json::Value& storage = Storage("concurrentViewers"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>concurrentViewers</code>' attribute. * * The number of viewers currently watching the broadcast. The property and * its value will be present if the broadcast has current viewers and the * broadcast owner has not hidden the viewcount for the video. Note that * YouTube stops tracking the number of concurrent viewers for a broadcast * when the broadcast ends. So, this property would not identify the number of * viewers watching an archived video of a live broadcast that already ended. * * @param[in] value The new value. */ void set_concurrent_viewers(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("concurrentViewers")); } /** * Determine if the '<code>totalChatCount</code>' attribute was set. * * @return true if the '<code>totalChatCount</code>' attribute was set. */ bool has_total_chat_count() const { return Storage().isMember("totalChatCount"); } /** * Clears the '<code>totalChatCount</code>' attribute. */ void clear_total_chat_count() { MutableStorage()->removeMember("totalChatCount"); } /** * Get the value of the '<code>totalChatCount</code>' attribute. */ uint64 get_total_chat_count() const { const Json::Value& storage = Storage("totalChatCount"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>totalChatCount</code>' attribute. * * The total number of live chat messages currently on the broadcast. The * property and its value will be present if the broadcast is public, has the * live chat feature enabled, and has at least one message. Note that this * field will not be filled after the broadcast ends. So this property would * not identify the number of chat messages for an archived video of a * completed live broadcast. * * @param[in] value The new value. */ void set_total_chat_count(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("totalChatCount")); } private: void operator=(const LiveBroadcastStatistics&); }; // LiveBroadcastStatistics } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_LIVE_BROADCAST_STATISTICS_H_ <file_sep>/src/samples/webflow_sample_main.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ // This sample shows different ways to use OAuth2 webflow. // Usage: // You need a client registered for hostname():port // // sample_webflow --logtostderr --client_secrets_path=... --port=... // // The --gplus_login determines whether this example will use // gplus_login (generally recommended) or a server-side mechanism // implemented by the sample for experimental and illustrative purposes. // // When it is running, you can run the following URLs from one or more // browsers with different users // // login to get credentials // me to see who you are (requires authentication already) // revoke to revoke access tokens // quit to quit // // // When pages are unauthorized the server will redirect to the login page // then redirect back. // The direct login page redirects to itself on success (as a welcome page). // The revoke page redirects to the login page (as a not-logged in page). // // For example try the following sequence // me will redirect to login // login will redirect back to me // revoke will redirect to login // login will redirect to itself (as welcome) // me (will show private details) // revoke will logout again // quit #include <stdlib.h> #include <cstdio> #include <map> #include <memory> #include <vector> #include <string> using std::string; #include "samples/abstract_gplus_login_flow.h" #include "samples/abstract_webserver_login_flow.h" #include "googleapis/client/auth/oauth2_authorization.h" #include "googleapis/client/auth/oauth2_pending_authorizations.h" #include "googleapis/client/data/data_reader.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/transport/curl_http_transport.h" #include "googleapis/client/transport/http_request.h" #include "googleapis/client/transport/http_response.h" #include "googleapis/client/transport/http_transport.h" #include "googleapis/client/util/mongoose_webserver.h" #include "googleapis/client/util/status.h" #include <gflags/gflags.h> #include <glog/logging.h> #include "googleapis/base/mutex.h" #include "googleapis/strings/split.h" #include "googleapis/strings/strip.h" #include "googleapis/strings/strcat.h" #include "googleapis/strings/util.h" namespace googleapis { DEFINE_bool(gplus_login, false, "Use Google+ Sig-In button if true." " By default it will use webserver_login"); DEFINE_int32(port, 8080, "The port to listen on must be registered" " for this host with the Google APIs Console" " for the service described in client_secrets_path"); DEFINE_string(client_secrets_path, "", "REQUIRED: Path to JSON client_secrets file for OAuth 2.0." " This can be downloaded comes from the Google APIs Console" " when you register this client application." " See //https://code.google.com/apis/console"); using sample::AbstractGplusLoginFlow; using sample::AbstractWebServerLoginFlow; using sample::WebServerRequest; using sample::WebServerResponse; using client::CurlHttpTransportFactory; using client::HttpTransportLayerConfig; using client::HttpRequest; using client::HttpResponse; using client::HttpStatusCode; using client::HttpTransport; using client::HttpTransportOptions; using client::MongooseWebServer; using client::OAuth2AuthorizationFlow; using client::OAuth2PendingAuthorizations; using client::OAuth2Credential; using client::OAuth2RequestOptions; using client::StatusOk; using client::StatusUnknown; /* * URL to get user info for login confirmation. */ const char kMeUrl[] = "https://www.googleapis.com/userinfo/v2/me"; /* * URL query parameter used for redirect urls. */ const char kLoginRedirectQueryParam[] = "redirect_uri"; /* * The OAuth scopes we'll ask for. */ const char kDefaultScopes[] = "https://www.googleapis.com/auth/userinfo.profile"; /* * We'll use this cookie to remember our cookie_id */ const char kCookieName[] = "SampleWorkflow"; class SampleWebApplication; /* * Stores application user data. * @ingroup Samples * * Each user will store their credentials here. * We'll also track the user name to confirm login. */ class UserData { public: /* * Default constructor for new users. */ UserData() { char tmp[40]; std::snprintf(tmp, sizeof(tmp), "%08lx%08lx%08lx%08lx", random(), random(), random(), random()); cookie_id_ = tmp; } /* * Standard constructor for returning users. * * @param[in] cookie_id Our user id was handed out as a cookie in an * earlier response */ explicit UserData(const string& cookie_id) : cookie_id_(cookie_id) { } /* * Standard destructor. */ virtual ~UserData() {} /* * Returns the cookie_id bound by the constructor. */ const string& cookie_id() const { return cookie_id_; } /* * Returns the Google Account id learned at login. */ const string& gid() const { return gid_; } /* * Sets the google account id for confirming future logins are not * reusing a cookie designating a different user. */ void set_gid(const string& id) { gid_ = id; } /* * Returns the real user's name. */ const string& user_name() const { return user_name_; } /* * Sets the real user's name, presumably from their Google Account. */ void set_user_name(const string& name) { user_name_ = name; } /* * Returns the credential for this user. * * @return NULL if the user is not actively logged in. */ OAuth2Credential* credential() { return credential_.get(); } /* * Resets the credential. * * @param[in] cred Should contain an access token. Ownership passed. */ void ResetCredential(OAuth2Credential* cred) { credential_.reset(cred); } private: /* * We're storing the cookie_id for logging and convienience. * We dont really need it here, just in repository mapping to this instance. * However since we want to return it as a cookie, it is convienent to * store here rather than propagating another parameter around. */ string cookie_id_; //< Our cookie_id (cookie value). string user_name_; //< Real user name (for confirming login). string gid_; //< Google account id (for confirmation). std::unique_ptr<OAuth2Credential> credential_; //< NULL when not logged in. }; /* * Repository managing UserData. * @ingroup Samples * * For purposes of this application we arent creating real users. * Instead we're treating the session as our user. We'll do extra work * to try to distinguish the current Google Account in the browser when * using the Google+ Login button (flag) but normally you would have your * own application user and tie that to a specific Google Account from the * authorization code when the user gave access. */ class UserRepository { public: /* * Standard constructor. * * @param[in] Transport to use for fetching user profile information. * Ownership is passed. * @param[in] verify_gid If true we should verify the credentials by * fetch Google Account id and comparing it to * previous. * * TODO(user): 20130608 * The means of verifying the user hers is not quite right. I think one * would normally use the id_token already returned from the g+ button * but I dont have support for the JWT decoding yet. I'm not sure how to * use CSRF tokens either. So we'll brute force verify the underlying acocunt * id's are consistent when we are pushed access tokens for a user. With a * more elaborate user model we could use these as the keys into our users * to be independent of the cookies, which could change over time and * across machines. Most real sites woudl have their own login and * independent user accounts. Here we are piggy backing off the google * account for simplicitly, but perhaps it is that which is causing confusion * when switching accounts within the same browser. */ explicit UserRepository(HttpTransport* transport, bool verify_gid) : transport_(transport), verify_gid_(verify_gid) { } /* * Standard destructor. */ ~UserRepository() { MutexLock l(&mutex_); // Cleanup the repository. // // We're deleting our user entries here, but leaving the access tokens // valid to expire. auto begin = repository_.begin(); auto end = repository_.end(); while (begin != end) { auto temp = begin; ++begin; delete temp->second; } } /* * Returns UserData instance for the given cookie_id. * * @parma[in] cookie_id NULL for a new user, * otherwise cookie_id from earlier UserData. * This is persistent so the UserData might not be in memory. * @return UserData managing the given cookie_id. */ UserData* GetUserDataFromCookieId(const string& cookie_id) { UserData* user_data; MutexLock l(&mutex_); if (!cookie_id.empty()) { std::map<string, UserData*>::iterator it = repository_.find(cookie_id); if (it != repository_.end()) { VLOG(1) << "Already have UserData for cookie=" << cookie_id; return it->second; } VLOG(1) << "Creating new UserData for existing cookie=" << cookie_id; user_data = new UserData(cookie_id); } else { user_data = new UserData; VLOG(1) << "Creating new UserData. cookie=" << user_data->cookie_id(); } repository_.insert(std::make_pair(user_data->cookie_id(), user_data)); return user_data; } googleapis::util::Status GetPersonalUserData( OAuth2Credential* cred, client::JsonCppDictionary* dict) { CHECK(cred != NULL); std::unique_ptr<HttpRequest> request( transport_->NewHttpRequest(HttpRequest::GET)); request->set_credential(cred); request->set_url(kMeUrl); googleapis::util::Status status = request->Execute(); if (!status.ok()) { LOG(ERROR) << "Failed invoking " << kMeUrl << status.error_message(); return status; } status = dict->LoadFromJsonReader(request->response()->body_reader()); // These are expected results from the URL we invoked. if (!dict->has("name")) { return StatusUnknown("name is missing!"); } if (!dict->has("id")) { return StatusUnknown("id is missing!"); } return StatusOk(); } /* * Adds credential for the user with the given_id. * * Creates the application user if it was not previously known. * * @param[in] cookie_id User to update. * @param[in] status ok if we have a credential, otherwise the failure. * @param[in] credential The credential to update, or NULL. */ bool AddCredential( const string& cookie_id, const googleapis::util::Status& status, OAuth2Credential* credential) { std::unique_ptr<OAuth2Credential> credential_deleter(credential); if (!status.ok()) { LOG(WARNING) << "Did not get credential for cookie=" << cookie_id << ": " << status.error_message(); return false; } UserData* user_data = GetUserDataFromCookieId(cookie_id); bool new_user = user_data->gid().empty(); if (new_user) { client::JsonCppCapsule< client::JsonCppDictionary> capsule; googleapis::util::Status status = GetPersonalUserData(credential, &capsule); if (!status.ok()) { LOG(ERROR) << "Could not get user data so removing user."; RemoveUser(cookie_id); return false; } user_data->set_user_name(capsule.as_value("name").asCString()); user_data->set_gid(capsule.as_value("id").asCString()); user_data->ResetCredential(credential_deleter.release()); } else if (verify_gid_) { // If the access tokens are the same then we're good. string old_access_token; OAuth2Credential* old_credential = user_data->credential(); if (old_credential) { old_access_token = old_credential->access_token().as_string(); } string new_access_token = credential->access_token().as_string(); if (old_access_token != new_access_token) { // If they are different, look for the underlying gid and see if // the user just refreshed the token. If not, swap out our user record. // Otherwise just keep the new credential. client::JsonCppCapsule< client::JsonCppDictionary> capsule; googleapis::util::Status status = GetPersonalUserData(credential, &capsule); if (!status.ok()) { LOG(ERROR) << "Could not get user data so removing user."; RemoveUser(cookie_id); return false; } string gid = capsule.as_value("id").asCString(); if (user_data->gid() != gid) { if (!user_data->gid().empty()) { LOG(WARNING) << "It appears user changed so swapping records."; RemoveUser(cookie_id); user_data = GetUserDataFromCookieId(cookie_id); } user_data->set_user_name(capsule.as_value("name").asCString()); user_data->set_gid(gid); new_user = true; } user_data->ResetCredential(credential_deleter.release()); } } else { // If we arent verifying the user, just swap the credential user_data->ResetCredential(credential_deleter.release()); } return !new_user; } void RemoveUser(const string& cookie_id) { MutexLock l(&mutex_); std::map<string, UserData*>::iterator found = repository_.find(cookie_id); if (found != repository_.end()) { delete found->second; repository_.erase(found); } } private: std::unique_ptr<HttpTransport> transport_; //< For getting user info. bool verify_gid_; //< Whether to verify gid Mutex mutex_; //< Protects repository std::map<string, UserData*> repository_ GUARDED_BY(mutex_); DISALLOW_COPY_AND_ASSIGN(UserRepository); }; template<class BASE> class SampleWebApplicationLoginFlow : public BASE { public: /* * Standard constructor. * @param[in] flow The OAuth 2.0 flow for getting and revoking * Access Tokens. The caller retains ownership. * @param[in] sample_app The flow will delegate the various page responses * to the application object itself. * The caller retains ownership. * @param[in] repository The flow will interact with the repository to * manage credentials. The caller retains ownership. */ SampleWebApplicationLoginFlow( OAuth2AuthorizationFlow* flow, SampleWebApplication* sample_app, // for shared response handling. UserRepository* repository) : BASE(kCookieName, kLoginRedirectQueryParam, flow), sample_app_(sample_app), user_repository_(repository) { } /* * Standard destructor. */ virtual ~SampleWebApplicationLoginFlow() {} SampleWebApplication* sample_app() const { return sample_app_; } UserRepository* user_repository() const { return user_repository_; } protected: /* * Hook for the base login flow to update credentials in the registry. * @param[in] cookie_id The application's user id being managed * @param[in] status If not ok then this is the error explaining a failure. * @param[in] credential If NULL the credential was revoked, * otherwise ownership is passed. */ virtual bool DoReceiveCredentialForCookieId( const string& cookie_id, const googleapis::util::Status& status, OAuth2Credential* credential) { if (credential) { return user_repository_->AddCredential(cookie_id, status, credential); } else { user_repository_->RemoveUser(cookie_id); return true; } } /* * Hook for the base login flow to get credentials for a given user. * * @return NULL if the user isnt actively logged in. */ virtual OAuth2Credential* DoGetCredentialForCookieId( const string& cookie_id) { return user_repository_->GetUserDataFromCookieId(cookie_id)->credential(); } /* * Hook for the base login flow to render a welcome page after login. */ virtual googleapis::util::Status DoRespondWithWelcomePage( const string& cookie_id, WebServerRequest* request); /* * Hook for the base login flow to render a login page. */ virtual googleapis::util::Status DoRespondWithNotLoggedInPage( const string& cookie_id, WebServerRequest* request); /* * Hook for the base login flow to render a login failure page. */ virtual googleapis::util::Status DoRespondWithLoginErrorPage( const string& cookie_id, const googleapis::util::Status& status, WebServerRequest* request); private: SampleWebApplication* sample_app_; UserRepository* user_repository_; DISALLOW_COPY_AND_ASSIGN(SampleWebApplicationLoginFlow); }; typedef SampleWebApplicationLoginFlow<AbstractWebServerLoginFlow> SampleMicroLoginFlow; typedef SampleWebApplicationLoginFlow<AbstractGplusLoginFlow> SampleGplusLoginFlow; /* * Our sample application just illustrates logging in to access * a protected page. * @defgroup Samples * * All protected pages redirect to the Login page when the user lacks * credentials. * * This class uses two separate login flow implementations for purposes of * illustration of two different approaches, their similarities and * differences. */ class SampleWebApplication { public: /* * Standard constructor also initializes application. */ SampleWebApplication() { httpd_.reset(new MongooseWebServer(FLAGS_port)); bool gplus_login = FLAGS_gplus_login; InitTransportLayer(); InitAuthorizationFlow(); user_repository_.reset( new UserRepository(config_->NewDefaultTransportOrDie(), true)); InitLoginFlow(gplus_login); // Add this last (after the login flow) so it has lower-prcedence. httpd_->AddPathHandler( "/", NewPermanentCallback(this, &SampleWebApplication::HandleDefaultUrls)); googleapis::util::Status status = httpd_->Startup(); CHECK(status.ok()) << status.error_message(); } /* * Standard destructor. */ ~SampleWebApplication() { } /* * Blocks this thread until the "quit" url signals it. * * The WebServer will use its own threads to process queriess. */ void Run() { MutexLock l(&mutex_); condvar_.Wait(&mutex_); } /* * Returns the UserData instance for the given request. * * Creates a new instance if one was not known already. * @param[in] request */ UserData* GetUserData(WebServerRequest* request) { string cookie_id; request->GetCookieValue(kCookieName, &cookie_id); // Empty if not there. return user_repository_->GetUserDataFromCookieId(cookie_id); } /* * Sends the welcome page back after user logs in. * * This is broken out so we can share it among the different * login mechanisms that the sample demonstrates. */ googleapis::util::Status RespondWithWelcomePage( UserData* user_data, WebServerRequest* request) { return RespondWithHtml(user_data, HttpStatusCode::OK, "Welcome!", request); } /* * Sends the "not logged in" page when user has no credentials. * * This is broken out so we can share it among the different * login mechanisms that the sample demonstrates. */ googleapis::util::Status RespondWithNotLoggedInPage( UserData* user_data, WebServerRequest* request) { string redirect_url; request->parsed_url().GetQueryParameter( kLoginRedirectQueryParam, &redirect_url); return RespondWithHtml( user_data, HttpStatusCode::OK, "You must first log in.", request, redirect_url); } /* * Sends the "login error" page when user has failed to login. * * This is broken out so we can share it among the different login * mechanisms that the sample demonstrates. */ googleapis::util::Status RespondWithLoginErrorPage( UserData* user_data, const googleapis::util::Status& status, WebServerRequest* request) { return RespondWithHtml( user_data, HttpStatusCode::UNAUTHORIZED, StrCat("Login error: ", status.error_message()), request); } private: /* * Helper function for initializing the transport layer. */ void InitTransportLayer() { config_.reset(new client::HttpTransportLayerConfig); client::HttpTransportFactory* factory = new client::CurlHttpTransportFactory(config_.get()); config_->ResetDefaultTransportFactory(factory); config_->mutable_default_transport_options()->set_cacerts_path( HttpTransportOptions::kDisableSslVerification); transport_.reset(config_->NewDefaultTransportOrDie()); } /* * Helper function for initializing the OAuth 2.0 authorization flow. */ void InitAuthorizationFlow() { CHECK(config_.get()) << "Must InitTransportLayer first"; googleapis::util::Status status; flow_.reset(OAuth2AuthorizationFlow::MakeFlowFromClientSecretsPath( FLAGS_client_secrets_path, config_->NewDefaultTransportOrDie(), &status)); CHECK(status.ok()) << status.error_message(); flow_->mutable_client_spec()->set_redirect_uri( httpd_->MakeEndpointUrl(false, "/oauth")); flow_->set_default_scopes(kDefaultScopes); } /* * Helper function for initializing the login component for our application. * * @param[in] use_gplus_login If true use Google+ Sign-in button, * otherwise do it directly within our server. */ void InitLoginFlow(bool use_gplus_login) { CHECK(httpd_.get()) << "Must initialize httpd_ first"; CHECK(flow_.get()) << "Must InitAuthorizationFlow first"; CHECK(user_repository_.get()) << "Must initialize user_repository_ first"; if (use_gplus_login) { gplus_login_.reset( new SampleGplusLoginFlow(flow_.get(), this, user_repository_.get())); gplus_login_->set_client_id(flow_->client_spec().client_id()); gplus_login_->set_scopes(kDefaultScopes); gplus_login_->set_log_to_console(true); gplus_login_->AddLoginUrl("/login", httpd_.get()); gplus_login_->AddLogoutUrl("/revoke", httpd_.get()); gplus_login_->AddReceiveAccessTokenUrl("/oauth", httpd_.get()); } else { login_.reset( new SampleMicroLoginFlow(flow_.get(), this, user_repository_.get())); login_->AddLoginUrl("/login", httpd_.get()); login_->AddLogoutUrl("/revoke", httpd_.get()); login_->AddReceiveAccessTokenUrl("/oauth", httpd_.get()); } } /* * Helper function for returning pages when using Google+ Sign-in button. * * @param[in] user_data The user data this page is for isnt always logged in. * @param[in] request The request we are responding to. * @param[in] redirect_success If non-empty then redirect here after login. * * @return HTML page to return will have $MSG_BODY to resolve. */ string MakeGplusPageTemplate( UserData* user_data, WebServerRequest* request, const string& redirect_success) { const string generic_template = "<html><head>\n$GOOGLE_PLUS_HEAD\n</head><body>\n" "$GOOGLE_PLUS_BUTTON\n" "<div>$USER_IDENTITY $LOGIN_CONTROL</div>\n" "<div id='msg_body'>$MSG_BODY</div>\n" "</body></html>\n"; const string& cookie_id = user_data->cookie_id(); string html; string success_block; string redirect_url = redirect_success; if (!user_data->credential() && redirect_success.empty()) { redirect_url ="/login"; } if (!redirect_url.empty()) { success_block = StrCat("window.location='", redirect_url, "'"); } string failure_block = "window.location='/login?error=' + error"; string immediate_block; if (user_data->credential()) { immediate_block = StrCat("window.location.replace='", request->parsed_url().url(), "'"); } string gplus_head = StrCat( gplus_login_->GetPrerequisiteHeadHtml(), gplus_login_->GetSigninCallbackJavascriptHtml( cookie_id, immediate_block, success_block, failure_block)); html = StringReplace( generic_template, "$GOOGLE_PLUS_HEAD", gplus_head, false); if (user_data->credential()) { html = StringReplace(html, "$LOGIN_CONTROL", "(<a href='/revoke'>Logout</a>)", false); } else { html = StringReplace(html, "$LOGIN_CONTROL", "", false); } // Dont show button by default. string gplus_button = gplus_login_->GetSigninButtonHtml(false); return StringReplace( html, "$GOOGLE_PLUS_BUTTON", gplus_button, false); } /* * Helper function for returning pages when using in-application login. * * @param[in] user_data The user data this page is for isnt always logged in. * @param[in] request The request we are responding to. * * @return HTML page to return will have * $MSG_BODY and $LOGIN_CONTROL to resolve. */ string MakeWebServerLoginPageTemplate( UserData* user_data, WebServerRequest* request) { const string generic_template = "<html><body>\n" "<div>$USER_IDENTITY ($LOGIN_CONTROL)</div>\n" "$MSG_BODY\n" "</body></html>\n"; string html; string escaped_login = client::EscapeForUrl("/login"); string redirect_to_login = StrCat(kLoginRedirectQueryParam, "=", escaped_login); if (user_data->credential()) { html = StringReplace( generic_template, "$LOGIN_CONTROL", StrCat("<a href='/revoke?", redirect_to_login, "'>Logout</a>"), false); } else { html = StringReplace( generic_template, "$LOGIN_CONTROL", StrCat("<a href='/login?", redirect_to_login, "'>Login</a>"), false); } return html; } /* * Responds to request with a [temporary] redirect. * * @param[in] user_data Contains this user's id for a cookie. * @param[in] url The url to redirect to. * @param[in] request The request we are responding to. * * @return ok or reason for failure. */ googleapis::util::Status RespondWithRedirect( UserData* user_data, const string& url, WebServerRequest* request) { LOG(INFO) << "Redirecting cookie=" << user_data->cookie_id() << " to " << url; WebServerResponse* response = request->response(); googleapis::util::Status status = response->AddCookie(kCookieName, user_data->cookie_id()); if (!status.ok()) { LOG(ERROR) << "Embedded webserver coudlnt add a cookie when redirecting:" << status.error_message(); // We'll still do the redirect though. } return response->SendRedirect(307, url); } /* * Responds to request with an HTML page. * * We're going to wrap the appliation's response with the login control. * * @param[in] user_data Contains information confirming login and add cookie. * @param[in] http_code The HTTP code to respond with. * @param[in] html_body The body of the page we're returning. * @param[in] request The request we are responding to. * * @return ok or reason for failure. */ googleapis::util::Status RespondWithHtml( UserData* user_data, int http_code, const string& html_body, WebServerRequest* request, string redirect_success = "") { string html = gplus_login_.get() ? MakeGplusPageTemplate(user_data, request, redirect_success) : MakeWebServerLoginPageTemplate(user_data, request); if (user_data->credential()) { const string& user_name = user_data->user_name(); string identity = StrCat("Logged in as <b>", user_name, "</b>"); html = StringReplace(html, "$USER_IDENTITY", identity, false); } else if (!gplus_login_.get()) { html = StringReplace(html, "$USER_IDENTITY", "<b>Not logged in</b>", false); } else { html = StringReplace(html, "$USER_IDENTITY", "", false); } html = StringReplace(html, "$MSG_BODY", html_body, false); WebServerResponse* response = request->response(); googleapis::util::Status status = response->AddCookie(kCookieName, user_data->cookie_id()); if (!status.ok()) { LOG(ERROR) << "Embedded webserver couldnt add a cookie. " << status.error_message(); // We'll still allow the request to continue though. } return response->SendHtml(http_code, html); } /* * Responds to /quit URL by quitting the server. * * @param[in] request The request we are responding to. * * @return ok or reason for failure. */ googleapis::util::Status ProcessQuitCommand(WebServerRequest* request) { MutexLock l(&mutex_); condvar_.Signal(); return request->response()->SendText( HttpStatusCode::OK, "Terminated server."); } /* * Responds to /me URL by displaying protected user data. * * @param[in] user_data Contains information to confirm login and add cookie. * It is assumed that the credential is already valid. * @param[in] request The request we are responding to. * * @return ok or reason for failure. */ googleapis::util::Status ProcessMeCommand( UserData* user_data, WebServerRequest* request) { std::unique_ptr<HttpRequest> http_request( transport_->NewHttpRequest(HttpRequest::GET)); http_request->set_url(kMeUrl); http_request->set_credential(user_data->credential()); http_request->Execute().IgnoreError(); int http_code = http_request->response()->http_code(); string msg; if (http_code) { msg = http_request->response()->body_reader()->RemainderToString(); } else { msg = StrCat("Could not execute: ", http_request->state().status().error_message()); } return RespondWithHtml(user_data, http_code, msg, request); } /* * Handles all the non-oauth callback urls int our sample application. * * @param[in] request The request we are responding to. * * @return ok or reason for failure. */ googleapis::util::Status HandleDefaultUrls(WebServerRequest* request) { VLOG(1) << "Default url handler=" << request->parsed_url().url(); // Strip leading "/" to get the command. string command = request->parsed_url().path().substr(1); if (command == "favicon.ico") { VLOG(1) << "Ignoring request=" << request->parsed_url().url(); return request->response()->SendText(HttpStatusCode::NOT_FOUND, ""); } else if (command == "quit") { return ProcessQuitCommand(request); } UserData* user_data = GetUserData(request); if (!user_data->credential()) { VLOG(1) << "No credential for " << user_data->cookie_id() << " so redirect"; string encoded_url = client::EscapeForUrl(request->parsed_url().url()); return RespondWithRedirect( user_data, StrCat("/login?", kLoginRedirectQueryParam, "=", encoded_url), request); } if (command == "me") { return ProcessMeCommand(user_data, request); } string msg = "Unrecognized command."; return RespondWithHtml( user_data, HttpStatusCode::NOT_FOUND, msg, request); } std::unique_ptr<MongooseWebServer> httpd_; std::unique_ptr<HttpTransport> transport_; std::unique_ptr<OAuth2AuthorizationFlow> flow_; std::unique_ptr<client::HttpTransportLayerConfig> config_; std::unique_ptr<UserRepository> user_repository_; // We'll be using one or the other of these depending on // FLAGS_gplus_login. std::unique_ptr<SampleMicroLoginFlow> login_; std::unique_ptr<SampleGplusLoginFlow> gplus_login_; Mutex mutex_; CondVar condvar_ GUARDED_BY(mutex_); DISALLOW_COPY_AND_ASSIGN(SampleWebApplication); }; template<class C> util::Status SampleWebApplicationLoginFlow<C>::DoRespondWithWelcomePage( const string& cookie_id, WebServerRequest* request) { UserData* user_data = user_repository_->GetUserDataFromCookieId(cookie_id); return sample_app_->RespondWithWelcomePage(user_data, request); } template<class C> util::Status SampleWebApplicationLoginFlow<C>::DoRespondWithNotLoggedInPage( const string& cookie_id, WebServerRequest* request) { UserData* user_data = user_repository_->GetUserDataFromCookieId(cookie_id); return sample_app_->RespondWithNotLoggedInPage(user_data, request); } template<class C> util::Status SampleWebApplicationLoginFlow<C>::DoRespondWithLoginErrorPage( const string& cookie_id, const googleapis::util::Status& status, WebServerRequest* request) { UserData* user_data = user_repository()->GetUserDataFromCookieId(cookie_id); return sample_app()->RespondWithLoginErrorPage(user_data, status, request); } } // namespace googleapis using namespace googleapis; int main(int argc, char* argv[]) { google::ParseCommandLineFlags(&argc, &argv, true); SampleWebApplication app; // Wait until "/quit" url is hit. app.Run(); return 0; } <file_sep>/service_apis/calendar/google/calendar_api/calendar_service.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // //------------------------------------------------------------------------------ // This code was generated by google-apis-code-generator 1.5.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. //------------------------------------------------------------------------------ #include "google/calendar_api/calendar_service.h" #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/client/service/client_service.h" #include "googleapis/client/service/service_request_pager.h" #include "googleapis/client/util/date_time.h" #include "googleapis/client/util/status.h" #include "google/calendar_api/acl.h" #include "google/calendar_api/acl_rule.h" #include "google/calendar_api/calendar.h" #include "google/calendar_api/calendar_list.h" #include "google/calendar_api/calendar_list_entry.h" #include "google/calendar_api/channel.h" #include "google/calendar_api/colors.h" #include "google/calendar_api/event.h" #include "google/calendar_api/events.h" #include "google/calendar_api/free_busy_request.h" #include "google/calendar_api/free_busy_response.h" #include "google/calendar_api/setting.h" #include "google/calendar_api/settings.h" #include "googleapis/client/data/data_reader.h" #include "googleapis/client/transport/http_request.h" #include "googleapis/client/transport/http_transport.h" #include "googleapis/client/util/uri_utils.h" #include "googleapis/strings/strcat.h" namespace google_calendar_api { using namespace googleapis; const char CalendarService::googleapis_API_NAME[] = {"calendar"}; const char CalendarService::googleapis_API_VERSION[] = {"v3"}; const char CalendarService::googleapis_API_GENERATOR[] = { "google-apis-code-generator 1.5.1 / 0.1.4"}; const char CalendarService::SCOPES::CALENDAR[] = {"https://www.googleapis.com/auth/calendar"}; const char CalendarService::SCOPES::CALENDAR_READONLY[] = {"https://www.googleapis.com/auth/calendar.readonly"}; CalendarServiceBaseRequest::CalendarServiceBaseRequest( const client::ClientService* service, client::AuthorizationCredential* credential, client::HttpRequest::HttpMethod method, const StringPiece& uri_template) : client::ClientServiceRequest( service, credential, method, uri_template), alt_("json"), pretty_print_(true), _have_alt_(false), _have_fields_(false), _have_key_(false), _have_oauth_token_(false), _have_pretty_print_(false), _have_quota_user_(false), _have_user_ip_(false) { } CalendarServiceBaseRequest::~CalendarServiceBaseRequest() { } util::Status CalendarServiceBaseRequest::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return client::StatusInvalidArgument( StrCat("Unknown url variable='", variable_name, "'")); } util::Status CalendarServiceBaseRequest::AppendOptionalQueryParameters( string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_alt_) { StrAppend(target, sep, "alt=", client::CppValueToEscapedUrlValue( alt_)); sep = "&"; } if (_have_fields_) { StrAppend(target, sep, "fields=", client::CppValueToEscapedUrlValue( fields_)); sep = "&"; } if (_have_key_) { StrAppend(target, sep, "key=", client::CppValueToEscapedUrlValue( key_)); sep = "&"; } if (_have_oauth_token_) { StrAppend(target, sep, "oauth_token=", client::CppValueToEscapedUrlValue( oauth_token_)); sep = "&"; } if (_have_pretty_print_) { StrAppend(target, sep, "prettyPrint=", client::CppValueToEscapedUrlValue( pretty_print_)); sep = "&"; } if (_have_quota_user_) { StrAppend(target, sep, "quotaUser=", client::CppValueToEscapedUrlValue( quota_user_)); sep = "&"; } if (_have_user_ip_) { StrAppend(target, sep, "userIp=", client::CppValueToEscapedUrlValue( user_ip_)); sep = "&"; } return client::ClientServiceRequest ::AppendOptionalQueryParameters(target); } void CalendarServiceBaseRequest::AddJsonContentToRequest( const client::JsonCppData *content) { client::HttpRequest* _http_request_ = mutable_http_request(); _http_request_->set_content_type( client::HttpRequest::ContentType_JSON); _http_request_->set_content_reader(content->MakeJsonReader()); } // Standard constructor. AclResource_DeleteMethod::AclResource_DeleteMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& rule_id) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "calendars/{calendarId}/acl/{ruleId}"), calendar_id_(calendar_id.as_string()), rule_id_(rule_id.as_string()) { } // Standard destructor. AclResource_DeleteMethod::~AclResource_DeleteMethod() { } util::Status AclResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } if (variable_name == "ruleId") { client::UriTemplate::AppendValue( rule_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. AclResource_GetMethod::AclResource_GetMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& rule_id) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "calendars/{calendarId}/acl/{ruleId}"), calendar_id_(calendar_id.as_string()), rule_id_(rule_id.as_string()) { } // Standard destructor. AclResource_GetMethod::~AclResource_GetMethod() { } util::Status AclResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } if (variable_name == "ruleId") { client::UriTemplate::AppendValue( rule_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. AclResource_InsertMethod::AclResource_InsertMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const AclRule& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "calendars/{calendarId}/acl"), calendar_id_(calendar_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. AclResource_InsertMethod::~AclResource_InsertMethod() { } util::Status AclResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. AclResource_ListMethod::AclResource_ListMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "calendars/{calendarId}/acl"), calendar_id_(calendar_id.as_string()), _have_max_results_(false), _have_page_token_(false), _have_show_deleted_(false), _have_sync_token_(false) { } // Standard destructor. AclResource_ListMethod::~AclResource_ListMethod() { } util::Status AclResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_show_deleted_) { StrAppend(target, sep, "showDeleted=", client::CppValueToEscapedUrlValue( show_deleted_)); sep = "&"; } if (_have_sync_token_) { StrAppend(target, sep, "syncToken=", client::CppValueToEscapedUrlValue( sync_token_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status AclResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. AclResource_PatchMethod::AclResource_PatchMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& rule_id, const AclRule& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::PATCH, "calendars/{calendarId}/acl/{ruleId}"), calendar_id_(calendar_id.as_string()), rule_id_(rule_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. AclResource_PatchMethod::~AclResource_PatchMethod() { } util::Status AclResource_PatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } if (variable_name == "ruleId") { client::UriTemplate::AppendValue( rule_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. AclResource_UpdateMethod::AclResource_UpdateMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& rule_id, const AclRule& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "calendars/{calendarId}/acl/{ruleId}"), calendar_id_(calendar_id.as_string()), rule_id_(rule_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. AclResource_UpdateMethod::~AclResource_UpdateMethod() { } util::Status AclResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } if (variable_name == "ruleId") { client::UriTemplate::AppendValue( rule_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. AclResource_WatchMethod::AclResource_WatchMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const Channel& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "calendars/{calendarId}/acl/watch"), calendar_id_(calendar_id.as_string()), _have_max_results_(false), _have_page_token_(false), _have_show_deleted_(false), _have_sync_token_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. AclResource_WatchMethod::~AclResource_WatchMethod() { } util::Status AclResource_WatchMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_show_deleted_) { StrAppend(target, sep, "showDeleted=", client::CppValueToEscapedUrlValue( show_deleted_)); sep = "&"; } if (_have_sync_token_) { StrAppend(target, sep, "syncToken=", client::CppValueToEscapedUrlValue( sync_token_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status AclResource_WatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CalendarListResource_DeleteMethod::CalendarListResource_DeleteMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "users/me/calendarList/{calendarId}"), calendar_id_(calendar_id.as_string()) { } // Standard destructor. CalendarListResource_DeleteMethod::~CalendarListResource_DeleteMethod() { } util::Status CalendarListResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CalendarListResource_GetMethod::CalendarListResource_GetMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "users/me/calendarList/{calendarId}"), calendar_id_(calendar_id.as_string()) { } // Standard destructor. CalendarListResource_GetMethod::~CalendarListResource_GetMethod() { } util::Status CalendarListResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CalendarListResource_InsertMethod::CalendarListResource_InsertMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const CalendarListEntry& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "users/me/calendarList"), _have_color_rgb_format_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. CalendarListResource_InsertMethod::~CalendarListResource_InsertMethod() { } util::Status CalendarListResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_color_rgb_format_) { StrAppend(target, sep, "colorRgbFormat=", client::CppValueToEscapedUrlValue( color_rgb_format_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CalendarListResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CalendarListResource_ListMethod::CalendarListResource_ListMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "users/me/calendarList"), _have_max_results_(false), _have_min_access_role_(false), _have_page_token_(false), _have_show_deleted_(false), _have_show_hidden_(false), _have_sync_token_(false) { } // Standard destructor. CalendarListResource_ListMethod::~CalendarListResource_ListMethod() { } util::Status CalendarListResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_min_access_role_) { StrAppend(target, sep, "minAccessRole=", client::CppValueToEscapedUrlValue( min_access_role_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_show_deleted_) { StrAppend(target, sep, "showDeleted=", client::CppValueToEscapedUrlValue( show_deleted_)); sep = "&"; } if (_have_show_hidden_) { StrAppend(target, sep, "showHidden=", client::CppValueToEscapedUrlValue( show_hidden_)); sep = "&"; } if (_have_sync_token_) { StrAppend(target, sep, "syncToken=", client::CppValueToEscapedUrlValue( sync_token_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CalendarListResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CalendarListResource_PatchMethod::CalendarListResource_PatchMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const CalendarListEntry& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::PATCH, "users/me/calendarList/{calendarId}"), calendar_id_(calendar_id.as_string()), _have_color_rgb_format_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. CalendarListResource_PatchMethod::~CalendarListResource_PatchMethod() { } util::Status CalendarListResource_PatchMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_color_rgb_format_) { StrAppend(target, sep, "colorRgbFormat=", client::CppValueToEscapedUrlValue( color_rgb_format_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CalendarListResource_PatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CalendarListResource_UpdateMethod::CalendarListResource_UpdateMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const CalendarListEntry& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "users/me/calendarList/{calendarId}"), calendar_id_(calendar_id.as_string()), _have_color_rgb_format_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. CalendarListResource_UpdateMethod::~CalendarListResource_UpdateMethod() { } util::Status CalendarListResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_color_rgb_format_) { StrAppend(target, sep, "colorRgbFormat=", client::CppValueToEscapedUrlValue( color_rgb_format_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CalendarListResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CalendarListResource_WatchMethod::CalendarListResource_WatchMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const Channel& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "users/me/calendarList/watch"), _have_max_results_(false), _have_min_access_role_(false), _have_page_token_(false), _have_show_deleted_(false), _have_show_hidden_(false), _have_sync_token_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. CalendarListResource_WatchMethod::~CalendarListResource_WatchMethod() { } util::Status CalendarListResource_WatchMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_min_access_role_) { StrAppend(target, sep, "minAccessRole=", client::CppValueToEscapedUrlValue( min_access_role_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_show_deleted_) { StrAppend(target, sep, "showDeleted=", client::CppValueToEscapedUrlValue( show_deleted_)); sep = "&"; } if (_have_show_hidden_) { StrAppend(target, sep, "showHidden=", client::CppValueToEscapedUrlValue( show_hidden_)); sep = "&"; } if (_have_sync_token_) { StrAppend(target, sep, "syncToken=", client::CppValueToEscapedUrlValue( sync_token_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CalendarListResource_WatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CalendarsResource_ClearMethod::CalendarsResource_ClearMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "calendars/{calendarId}/clear"), calendar_id_(calendar_id.as_string()) { } // Standard destructor. CalendarsResource_ClearMethod::~CalendarsResource_ClearMethod() { } util::Status CalendarsResource_ClearMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CalendarsResource_DeleteMethod::CalendarsResource_DeleteMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "calendars/{calendarId}"), calendar_id_(calendar_id.as_string()) { } // Standard destructor. CalendarsResource_DeleteMethod::~CalendarsResource_DeleteMethod() { } util::Status CalendarsResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CalendarsResource_GetMethod::CalendarsResource_GetMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "calendars/{calendarId}"), calendar_id_(calendar_id.as_string()) { } // Standard destructor. CalendarsResource_GetMethod::~CalendarsResource_GetMethod() { } util::Status CalendarsResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CalendarsResource_InsertMethod::CalendarsResource_InsertMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const Calendar& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "calendars") { AddJsonContentToRequest(&__request_content__); } // Standard destructor. CalendarsResource_InsertMethod::~CalendarsResource_InsertMethod() { } // Standard constructor. CalendarsResource_PatchMethod::CalendarsResource_PatchMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const Calendar& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::PATCH, "calendars/{calendarId}"), calendar_id_(calendar_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. CalendarsResource_PatchMethod::~CalendarsResource_PatchMethod() { } util::Status CalendarsResource_PatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CalendarsResource_UpdateMethod::CalendarsResource_UpdateMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const Calendar& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "calendars/{calendarId}"), calendar_id_(calendar_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. CalendarsResource_UpdateMethod::~CalendarsResource_UpdateMethod() { } util::Status CalendarsResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ChannelsResource_StopMethod::ChannelsResource_StopMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const Channel& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "channels/stop") { AddJsonContentToRequest(&__request_content__); } // Standard destructor. ChannelsResource_StopMethod::~ChannelsResource_StopMethod() { } // Standard constructor. ColorsResource_GetMethod::ColorsResource_GetMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "colors") { } // Standard destructor. ColorsResource_GetMethod::~ColorsResource_GetMethod() { } // Standard constructor. EventsResource_DeleteMethod::EventsResource_DeleteMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& event_id) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "calendars/{calendarId}/events/{eventId}"), calendar_id_(calendar_id.as_string()), event_id_(event_id.as_string()), _have_send_notifications_(false) { } // Standard destructor. EventsResource_DeleteMethod::~EventsResource_DeleteMethod() { } util::Status EventsResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_send_notifications_) { StrAppend(target, sep, "sendNotifications=", client::CppValueToEscapedUrlValue( send_notifications_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status EventsResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } if (variable_name == "eventId") { client::UriTemplate::AppendValue( event_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. EventsResource_GetMethod::EventsResource_GetMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& event_id) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "calendars/{calendarId}/events/{eventId}"), calendar_id_(calendar_id.as_string()), event_id_(event_id.as_string()), _have_always_include_email_(false), _have_max_attendees_(false), _have_time_zone_(false) { } // Standard destructor. EventsResource_GetMethod::~EventsResource_GetMethod() { } util::Status EventsResource_GetMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_always_include_email_) { StrAppend(target, sep, "alwaysIncludeEmail=", client::CppValueToEscapedUrlValue( always_include_email_)); sep = "&"; } if (_have_max_attendees_) { StrAppend(target, sep, "maxAttendees=", client::CppValueToEscapedUrlValue( max_attendees_)); sep = "&"; } if (_have_time_zone_) { StrAppend(target, sep, "timeZone=", client::CppValueToEscapedUrlValue( time_zone_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status EventsResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } if (variable_name == "eventId") { client::UriTemplate::AppendValue( event_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. EventsResource_ImportMethod::EventsResource_ImportMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const Event& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "calendars/{calendarId}/events/import"), calendar_id_(calendar_id.as_string()), _have_supports_attachments_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. EventsResource_ImportMethod::~EventsResource_ImportMethod() { } util::Status EventsResource_ImportMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_supports_attachments_) { StrAppend(target, sep, "supportsAttachments=", client::CppValueToEscapedUrlValue( supports_attachments_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status EventsResource_ImportMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. EventsResource_InsertMethod::EventsResource_InsertMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const Event& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "calendars/{calendarId}/events"), calendar_id_(calendar_id.as_string()), _have_max_attendees_(false), _have_send_notifications_(false), _have_supports_attachments_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. EventsResource_InsertMethod::~EventsResource_InsertMethod() { } util::Status EventsResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_max_attendees_) { StrAppend(target, sep, "maxAttendees=", client::CppValueToEscapedUrlValue( max_attendees_)); sep = "&"; } if (_have_send_notifications_) { StrAppend(target, sep, "sendNotifications=", client::CppValueToEscapedUrlValue( send_notifications_)); sep = "&"; } if (_have_supports_attachments_) { StrAppend(target, sep, "supportsAttachments=", client::CppValueToEscapedUrlValue( supports_attachments_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status EventsResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. EventsResource_InstancesMethod::EventsResource_InstancesMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& event_id) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "calendars/{calendarId}/events/{eventId}/instances"), calendar_id_(calendar_id.as_string()), event_id_(event_id.as_string()), _have_always_include_email_(false), _have_max_attendees_(false), _have_max_results_(false), _have_original_start_(false), _have_page_token_(false), _have_show_deleted_(false), _have_time_max_(false), _have_time_min_(false), _have_time_zone_(false) { } // Standard destructor. EventsResource_InstancesMethod::~EventsResource_InstancesMethod() { } util::Status EventsResource_InstancesMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_always_include_email_) { StrAppend(target, sep, "alwaysIncludeEmail=", client::CppValueToEscapedUrlValue( always_include_email_)); sep = "&"; } if (_have_max_attendees_) { StrAppend(target, sep, "maxAttendees=", client::CppValueToEscapedUrlValue( max_attendees_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_original_start_) { StrAppend(target, sep, "originalStart=", client::CppValueToEscapedUrlValue( original_start_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_show_deleted_) { StrAppend(target, sep, "showDeleted=", client::CppValueToEscapedUrlValue( show_deleted_)); sep = "&"; } if (_have_time_max_) { StrAppend(target, sep, "timeMax=", client::CppValueToEscapedUrlValue( time_max_)); sep = "&"; } if (_have_time_min_) { StrAppend(target, sep, "timeMin=", client::CppValueToEscapedUrlValue( time_min_)); sep = "&"; } if (_have_time_zone_) { StrAppend(target, sep, "timeZone=", client::CppValueToEscapedUrlValue( time_zone_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status EventsResource_InstancesMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } if (variable_name == "eventId") { client::UriTemplate::AppendValue( event_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. EventsResource_ListMethod::EventsResource_ListMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "calendars/{calendarId}/events"), calendar_id_(calendar_id.as_string()), max_results_(250), _have_always_include_email_(false), _have_i_cal_uid_(false), _have_max_attendees_(false), _have_max_results_(false), _have_order_by_(false), _have_page_token_(false), _have_private_extended_property_(false), _have_q_(false), _have_shared_extended_property_(false), _have_show_deleted_(false), _have_show_hidden_invitations_(false), _have_single_events_(false), _have_sync_token_(false), _have_time_max_(false), _have_time_min_(false), _have_time_zone_(false), _have_updated_min_(false) { } // Standard destructor. EventsResource_ListMethod::~EventsResource_ListMethod() { } util::Status EventsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_always_include_email_) { StrAppend(target, sep, "alwaysIncludeEmail=", client::CppValueToEscapedUrlValue( always_include_email_)); sep = "&"; } if (_have_i_cal_uid_) { StrAppend(target, sep, "iCalUID=", client::CppValueToEscapedUrlValue( i_cal_uid_)); sep = "&"; } if (_have_max_attendees_) { StrAppend(target, sep, "maxAttendees=", client::CppValueToEscapedUrlValue( max_attendees_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_order_by_) { StrAppend(target, sep, "orderBy=", client::CppValueToEscapedUrlValue( order_by_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_private_extended_property_) { if (!private_extended_property_.empty()) { target->append(sep); client::AppendIteratorToUrl( private_extended_property_.begin(), private_extended_property_.end(), "privateExtendedProperty", target); sep = "&"; } } if (_have_q_) { StrAppend(target, sep, "q=", client::CppValueToEscapedUrlValue( q_)); sep = "&"; } if (_have_shared_extended_property_) { if (!shared_extended_property_.empty()) { target->append(sep); client::AppendIteratorToUrl( shared_extended_property_.begin(), shared_extended_property_.end(), "sharedExtendedProperty", target); sep = "&"; } } if (_have_show_deleted_) { StrAppend(target, sep, "showDeleted=", client::CppValueToEscapedUrlValue( show_deleted_)); sep = "&"; } if (_have_show_hidden_invitations_) { StrAppend(target, sep, "showHiddenInvitations=", client::CppValueToEscapedUrlValue( show_hidden_invitations_)); sep = "&"; } if (_have_single_events_) { StrAppend(target, sep, "singleEvents=", client::CppValueToEscapedUrlValue( single_events_)); sep = "&"; } if (_have_sync_token_) { StrAppend(target, sep, "syncToken=", client::CppValueToEscapedUrlValue( sync_token_)); sep = "&"; } if (_have_time_max_) { StrAppend(target, sep, "timeMax=", client::CppValueToEscapedUrlValue( time_max_)); sep = "&"; } if (_have_time_min_) { StrAppend(target, sep, "timeMin=", client::CppValueToEscapedUrlValue( time_min_)); sep = "&"; } if (_have_time_zone_) { StrAppend(target, sep, "timeZone=", client::CppValueToEscapedUrlValue( time_zone_)); sep = "&"; } if (_have_updated_min_) { StrAppend(target, sep, "updatedMin=", client::CppValueToEscapedUrlValue( updated_min_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status EventsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. EventsResource_MoveMethod::EventsResource_MoveMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& event_id, const StringPiece& destination) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "calendars/{calendarId}/events/{eventId}/move"), calendar_id_(calendar_id.as_string()), event_id_(event_id.as_string()), destination_(destination.as_string()), _have_send_notifications_(false) { } // Standard destructor. EventsResource_MoveMethod::~EventsResource_MoveMethod() { } util::Status EventsResource_MoveMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "destination=", client::CppValueToEscapedUrlValue( destination_)); sep = "&"; if (_have_send_notifications_) { StrAppend(target, sep, "sendNotifications=", client::CppValueToEscapedUrlValue( send_notifications_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status EventsResource_MoveMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } if (variable_name == "eventId") { client::UriTemplate::AppendValue( event_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. EventsResource_PatchMethod::EventsResource_PatchMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& event_id, const Event& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::PATCH, "calendars/{calendarId}/events/{eventId}"), calendar_id_(calendar_id.as_string()), event_id_(event_id.as_string()), _have_always_include_email_(false), _have_max_attendees_(false), _have_send_notifications_(false), _have_supports_attachments_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. EventsResource_PatchMethod::~EventsResource_PatchMethod() { } util::Status EventsResource_PatchMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_always_include_email_) { StrAppend(target, sep, "alwaysIncludeEmail=", client::CppValueToEscapedUrlValue( always_include_email_)); sep = "&"; } if (_have_max_attendees_) { StrAppend(target, sep, "maxAttendees=", client::CppValueToEscapedUrlValue( max_attendees_)); sep = "&"; } if (_have_send_notifications_) { StrAppend(target, sep, "sendNotifications=", client::CppValueToEscapedUrlValue( send_notifications_)); sep = "&"; } if (_have_supports_attachments_) { StrAppend(target, sep, "supportsAttachments=", client::CppValueToEscapedUrlValue( supports_attachments_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status EventsResource_PatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } if (variable_name == "eventId") { client::UriTemplate::AppendValue( event_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. EventsResource_QuickAddMethod::EventsResource_QuickAddMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& text) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "calendars/{calendarId}/events/quickAdd"), calendar_id_(calendar_id.as_string()), text_(text.as_string()), _have_send_notifications_(false) { } // Standard destructor. EventsResource_QuickAddMethod::~EventsResource_QuickAddMethod() { } util::Status EventsResource_QuickAddMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "text=", client::CppValueToEscapedUrlValue( text_)); sep = "&"; if (_have_send_notifications_) { StrAppend(target, sep, "sendNotifications=", client::CppValueToEscapedUrlValue( send_notifications_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status EventsResource_QuickAddMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. EventsResource_UpdateMethod::EventsResource_UpdateMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& event_id, const Event& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "calendars/{calendarId}/events/{eventId}"), calendar_id_(calendar_id.as_string()), event_id_(event_id.as_string()), _have_always_include_email_(false), _have_max_attendees_(false), _have_send_notifications_(false), _have_supports_attachments_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. EventsResource_UpdateMethod::~EventsResource_UpdateMethod() { } util::Status EventsResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_always_include_email_) { StrAppend(target, sep, "alwaysIncludeEmail=", client::CppValueToEscapedUrlValue( always_include_email_)); sep = "&"; } if (_have_max_attendees_) { StrAppend(target, sep, "maxAttendees=", client::CppValueToEscapedUrlValue( max_attendees_)); sep = "&"; } if (_have_send_notifications_) { StrAppend(target, sep, "sendNotifications=", client::CppValueToEscapedUrlValue( send_notifications_)); sep = "&"; } if (_have_supports_attachments_) { StrAppend(target, sep, "supportsAttachments=", client::CppValueToEscapedUrlValue( supports_attachments_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status EventsResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } if (variable_name == "eventId") { client::UriTemplate::AppendValue( event_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. EventsResource_WatchMethod::EventsResource_WatchMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const Channel& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "calendars/{calendarId}/events/watch"), calendar_id_(calendar_id.as_string()), max_results_(250), _have_always_include_email_(false), _have_i_cal_uid_(false), _have_max_attendees_(false), _have_max_results_(false), _have_order_by_(false), _have_page_token_(false), _have_private_extended_property_(false), _have_q_(false), _have_shared_extended_property_(false), _have_show_deleted_(false), _have_show_hidden_invitations_(false), _have_single_events_(false), _have_sync_token_(false), _have_time_max_(false), _have_time_min_(false), _have_time_zone_(false), _have_updated_min_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. EventsResource_WatchMethod::~EventsResource_WatchMethod() { } util::Status EventsResource_WatchMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_always_include_email_) { StrAppend(target, sep, "alwaysIncludeEmail=", client::CppValueToEscapedUrlValue( always_include_email_)); sep = "&"; } if (_have_i_cal_uid_) { StrAppend(target, sep, "iCalUID=", client::CppValueToEscapedUrlValue( i_cal_uid_)); sep = "&"; } if (_have_max_attendees_) { StrAppend(target, sep, "maxAttendees=", client::CppValueToEscapedUrlValue( max_attendees_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_order_by_) { StrAppend(target, sep, "orderBy=", client::CppValueToEscapedUrlValue( order_by_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_private_extended_property_) { if (!private_extended_property_.empty()) { target->append(sep); client::AppendIteratorToUrl( private_extended_property_.begin(), private_extended_property_.end(), "privateExtendedProperty", target); sep = "&"; } } if (_have_q_) { StrAppend(target, sep, "q=", client::CppValueToEscapedUrlValue( q_)); sep = "&"; } if (_have_shared_extended_property_) { if (!shared_extended_property_.empty()) { target->append(sep); client::AppendIteratorToUrl( shared_extended_property_.begin(), shared_extended_property_.end(), "sharedExtendedProperty", target); sep = "&"; } } if (_have_show_deleted_) { StrAppend(target, sep, "showDeleted=", client::CppValueToEscapedUrlValue( show_deleted_)); sep = "&"; } if (_have_show_hidden_invitations_) { StrAppend(target, sep, "showHiddenInvitations=", client::CppValueToEscapedUrlValue( show_hidden_invitations_)); sep = "&"; } if (_have_single_events_) { StrAppend(target, sep, "singleEvents=", client::CppValueToEscapedUrlValue( single_events_)); sep = "&"; } if (_have_sync_token_) { StrAppend(target, sep, "syncToken=", client::CppValueToEscapedUrlValue( sync_token_)); sep = "&"; } if (_have_time_max_) { StrAppend(target, sep, "timeMax=", client::CppValueToEscapedUrlValue( time_max_)); sep = "&"; } if (_have_time_min_) { StrAppend(target, sep, "timeMin=", client::CppValueToEscapedUrlValue( time_min_)); sep = "&"; } if (_have_time_zone_) { StrAppend(target, sep, "timeZone=", client::CppValueToEscapedUrlValue( time_zone_)); sep = "&"; } if (_have_updated_min_) { StrAppend(target, sep, "updatedMin=", client::CppValueToEscapedUrlValue( updated_min_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status EventsResource_WatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "calendarId") { client::UriTemplate::AppendValue( calendar_id_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. FreebusyResource_QueryMethod::FreebusyResource_QueryMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const FreeBusyRequest& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "freeBusy") { AddJsonContentToRequest(&__request_content__); } // Standard destructor. FreebusyResource_QueryMethod::~FreebusyResource_QueryMethod() { } // Standard constructor. SettingsResource_GetMethod::SettingsResource_GetMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& setting) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "users/me/settings/{setting}"), setting_(setting.as_string()) { } // Standard destructor. SettingsResource_GetMethod::~SettingsResource_GetMethod() { } util::Status SettingsResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "setting") { client::UriTemplate::AppendValue( setting_, config, target); return client::StatusOk(); } return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. SettingsResource_ListMethod::SettingsResource_ListMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "users/me/settings"), _have_max_results_(false), _have_page_token_(false), _have_sync_token_(false) { } // Standard destructor. SettingsResource_ListMethod::~SettingsResource_ListMethod() { } util::Status SettingsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_sync_token_) { StrAppend(target, sep, "syncToken=", client::CppValueToEscapedUrlValue( sync_token_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status SettingsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. SettingsResource_WatchMethod::SettingsResource_WatchMethod( const CalendarService* _service_, client::AuthorizationCredential* _credential_, const Channel& __request_content__) : CalendarServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "users/me/settings/watch"), _have_max_results_(false), _have_page_token_(false), _have_sync_token_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. SettingsResource_WatchMethod::~SettingsResource_WatchMethod() { } util::Status SettingsResource_WatchMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_sync_token_) { StrAppend(target, sep, "syncToken=", client::CppValueToEscapedUrlValue( sync_token_)); sep = "&"; } return CalendarServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status SettingsResource_WatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return CalendarServiceBaseRequest::AppendVariable( variable_name, config, target); } CalendarService::CalendarService(client::HttpTransport* transport) : ClientService("https://www.googleapis.com/", "calendar/v3/", transport), acl_(this), calendar_list_(this), calendars_(this), channels_(this), colors_(this), events_(this), freebusy_(this), settings_(this) { } CalendarService::~CalendarService() { } CalendarService::AclResource::AclResource(CalendarService* service) : service_(service) { } AclResource_DeleteMethod* CalendarService::AclResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& rule_id) const { return new AclResource_DeleteMethod(service_, _credential_, calendar_id, rule_id); } AclResource_GetMethod* CalendarService::AclResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& rule_id) const { return new AclResource_GetMethod(service_, _credential_, calendar_id, rule_id); } AclResource_InsertMethod* CalendarService::AclResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const AclRule& __request_content__) const { return new AclResource_InsertMethod(service_, _credential_, calendar_id, __request_content__); } AclResource_ListMethod* CalendarService::AclResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) const { return new AclResource_ListMethod(service_, _credential_, calendar_id); } AclResource_ListMethodPager* CalendarService::AclResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) const { return new client::EncapsulatedServiceRequestPager<AclResource_ListMethod, Acl>(new AclResource_ListMethod(service_, _credential_, calendar_id)); } AclResource_PatchMethod* CalendarService::AclResource::NewPatchMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& rule_id, const AclRule& __request_content__) const { return new AclResource_PatchMethod(service_, _credential_, calendar_id, rule_id, __request_content__); } AclResource_UpdateMethod* CalendarService::AclResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& rule_id, const AclRule& __request_content__) const { return new AclResource_UpdateMethod(service_, _credential_, calendar_id, rule_id, __request_content__); } AclResource_WatchMethod* CalendarService::AclResource::NewWatchMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const Channel& __request_content__) const { return new AclResource_WatchMethod(service_, _credential_, calendar_id, __request_content__); } CalendarService::CalendarListResource::CalendarListResource(CalendarService* service) : service_(service) { } CalendarListResource_DeleteMethod* CalendarService::CalendarListResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) const { return new CalendarListResource_DeleteMethod(service_, _credential_, calendar_id); } CalendarListResource_GetMethod* CalendarService::CalendarListResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) const { return new CalendarListResource_GetMethod(service_, _credential_, calendar_id); } CalendarListResource_InsertMethod* CalendarService::CalendarListResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const CalendarListEntry& __request_content__) const { return new CalendarListResource_InsertMethod(service_, _credential_, __request_content__); } CalendarListResource_ListMethod* CalendarService::CalendarListResource::NewListMethod(client::AuthorizationCredential* _credential_) const { return new CalendarListResource_ListMethod(service_, _credential_); } CalendarListResource_ListMethodPager* CalendarService::CalendarListResource::NewListMethodPager(client::AuthorizationCredential* _credential_) const { return new client::EncapsulatedServiceRequestPager<CalendarListResource_ListMethod, CalendarList>(new CalendarListResource_ListMethod(service_, _credential_)); } CalendarListResource_PatchMethod* CalendarService::CalendarListResource::NewPatchMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const CalendarListEntry& __request_content__) const { return new CalendarListResource_PatchMethod(service_, _credential_, calendar_id, __request_content__); } CalendarListResource_UpdateMethod* CalendarService::CalendarListResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const CalendarListEntry& __request_content__) const { return new CalendarListResource_UpdateMethod(service_, _credential_, calendar_id, __request_content__); } CalendarListResource_WatchMethod* CalendarService::CalendarListResource::NewWatchMethod(client::AuthorizationCredential* _credential_, const Channel& __request_content__) const { return new CalendarListResource_WatchMethod(service_, _credential_, __request_content__); } CalendarService::CalendarsResource::CalendarsResource(CalendarService* service) : service_(service) { } CalendarsResource_ClearMethod* CalendarService::CalendarsResource::NewClearMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) const { return new CalendarsResource_ClearMethod(service_, _credential_, calendar_id); } CalendarsResource_DeleteMethod* CalendarService::CalendarsResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) const { return new CalendarsResource_DeleteMethod(service_, _credential_, calendar_id); } CalendarsResource_GetMethod* CalendarService::CalendarsResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) const { return new CalendarsResource_GetMethod(service_, _credential_, calendar_id); } CalendarsResource_InsertMethod* CalendarService::CalendarsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const Calendar& __request_content__) const { return new CalendarsResource_InsertMethod(service_, _credential_, __request_content__); } CalendarsResource_PatchMethod* CalendarService::CalendarsResource::NewPatchMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const Calendar& __request_content__) const { return new CalendarsResource_PatchMethod(service_, _credential_, calendar_id, __request_content__); } CalendarsResource_UpdateMethod* CalendarService::CalendarsResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const Calendar& __request_content__) const { return new CalendarsResource_UpdateMethod(service_, _credential_, calendar_id, __request_content__); } CalendarService::ChannelsResource::ChannelsResource(CalendarService* service) : service_(service) { } ChannelsResource_StopMethod* CalendarService::ChannelsResource::NewStopMethod(client::AuthorizationCredential* _credential_, const Channel& __request_content__) const { return new ChannelsResource_StopMethod(service_, _credential_, __request_content__); } CalendarService::ColorsResource::ColorsResource(CalendarService* service) : service_(service) { } ColorsResource_GetMethod* CalendarService::ColorsResource::NewGetMethod(client::AuthorizationCredential* _credential_) const { return new ColorsResource_GetMethod(service_, _credential_); } CalendarService::EventsResource::EventsResource(CalendarService* service) : service_(service) { } EventsResource_DeleteMethod* CalendarService::EventsResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& event_id) const { return new EventsResource_DeleteMethod(service_, _credential_, calendar_id, event_id); } EventsResource_GetMethod* CalendarService::EventsResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& event_id) const { return new EventsResource_GetMethod(service_, _credential_, calendar_id, event_id); } EventsResource_ImportMethod* CalendarService::EventsResource::NewImportMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const Event& __request_content__) const { return new EventsResource_ImportMethod(service_, _credential_, calendar_id, __request_content__); } EventsResource_InsertMethod* CalendarService::EventsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const Event& __request_content__) const { return new EventsResource_InsertMethod(service_, _credential_, calendar_id, __request_content__); } EventsResource_InstancesMethod* CalendarService::EventsResource::NewInstancesMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& event_id) const { return new EventsResource_InstancesMethod(service_, _credential_, calendar_id, event_id); } EventsResource_InstancesMethodPager* CalendarService::EventsResource::NewInstancesMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& event_id) const { return new client::EncapsulatedServiceRequestPager<EventsResource_InstancesMethod, Events>(new EventsResource_InstancesMethod(service_, _credential_, calendar_id, event_id)); } EventsResource_ListMethod* CalendarService::EventsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) const { return new EventsResource_ListMethod(service_, _credential_, calendar_id); } EventsResource_ListMethodPager* CalendarService::EventsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id) const { return new client::EncapsulatedServiceRequestPager<EventsResource_ListMethod, Events>(new EventsResource_ListMethod(service_, _credential_, calendar_id)); } EventsResource_MoveMethod* CalendarService::EventsResource::NewMoveMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& event_id, const StringPiece& destination) const { return new EventsResource_MoveMethod(service_, _credential_, calendar_id, event_id, destination); } EventsResource_PatchMethod* CalendarService::EventsResource::NewPatchMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& event_id, const Event& __request_content__) const { return new EventsResource_PatchMethod(service_, _credential_, calendar_id, event_id, __request_content__); } EventsResource_QuickAddMethod* CalendarService::EventsResource::NewQuickAddMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& text) const { return new EventsResource_QuickAddMethod(service_, _credential_, calendar_id, text); } EventsResource_UpdateMethod* CalendarService::EventsResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const StringPiece& event_id, const Event& __request_content__) const { return new EventsResource_UpdateMethod(service_, _credential_, calendar_id, event_id, __request_content__); } EventsResource_WatchMethod* CalendarService::EventsResource::NewWatchMethod(client::AuthorizationCredential* _credential_, const StringPiece& calendar_id, const Channel& __request_content__) const { return new EventsResource_WatchMethod(service_, _credential_, calendar_id, __request_content__); } CalendarService::FreebusyResource::FreebusyResource(CalendarService* service) : service_(service) { } FreebusyResource_QueryMethod* CalendarService::FreebusyResource::NewQueryMethod(client::AuthorizationCredential* _credential_, const FreeBusyRequest& __request_content__) const { return new FreebusyResource_QueryMethod(service_, _credential_, __request_content__); } CalendarService::SettingsResource::SettingsResource(CalendarService* service) : service_(service) { } SettingsResource_GetMethod* CalendarService::SettingsResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& setting) const { return new SettingsResource_GetMethod(service_, _credential_, setting); } SettingsResource_ListMethod* CalendarService::SettingsResource::NewListMethod(client::AuthorizationCredential* _credential_) const { return new SettingsResource_ListMethod(service_, _credential_); } SettingsResource_ListMethodPager* CalendarService::SettingsResource::NewListMethodPager(client::AuthorizationCredential* _credential_) const { return new client::EncapsulatedServiceRequestPager<SettingsResource_ListMethod, Settings>(new SettingsResource_ListMethod(service_, _credential_)); } SettingsResource_WatchMethod* CalendarService::SettingsResource::NewWatchMethod(client::AuthorizationCredential* _credential_, const Channel& __request_content__) const { return new SettingsResource_WatchMethod(service_, _credential_, __request_content__); } } // namespace google_calendar_api <file_sep>/src/googleapis/client/util/mongoose_webserver.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <map> #include <string> using std::string; #include <vector> #include "googleapis/client/util/mongoose_webserver.h" #include "googleapis/client/util/uri_utils.h" #include "googleapis/client/util/status.h" #include <glog/logging.h> #include "googleapis/strings/numbers.h" #include "googleapis/strings/strcat.h" namespace googleapis { namespace client { static inline string OriginalUri(const struct mg_request_info* request_info) { if (request_info->query_string && *request_info->query_string) { return StrCat(request_info->uri, "?", request_info->query_string); } else { return request_info->uri; } } class MongooseResponse : public WebServerResponse { public: explicit MongooseResponse(struct mg_connection* connection) : connection_(connection) { } virtual ~MongooseResponse() {} struct mg_connection* connection() { return connection_; } virtual googleapis::util::Status SendReply( const string& content_type, int http_code, const string& payload) { const string& http_code_msg = HttpCodeToHttpErrorMessage(http_code); string headers = StrCat("HTTP/1.1 ", http_code, " ", http_code_msg, "\r\n"); StrAppend(&headers, "Content-Type: ", content_type, "\r\n", "Content-Length: ", payload.size(), "\r\n"); for (auto it = headers_.begin(); it != headers_.end(); ++it) { StrAppend(&headers, it->first, ": ", it->second, "\r\n"); } for (std::vector<string>::const_iterator it = cookies_.begin(); it != cookies_.end(); ++it) { StrAppend(&headers, "Set-Cookie:", *it, "\r\n"); } StrAppend(&headers, "\r\n"); int wrote = mg_write(connection_, headers.c_str(), headers.size()); if (wrote != headers.size()) { if (wrote == 0) return StatusAborted("Connection was closed"); if (wrote < 0) return StatusUnknown("Error sending response"); return StatusUnknown( StrCat("Only send ", wrote, " of ", headers.size())); } if (payload.size()) { wrote = mg_write(connection_, payload.data(), payload.size()); if (wrote != headers.size()) { if (wrote == 0) return StatusAborted("Connection was closed"); if (wrote < 0) return StatusUnknown("Error sending response"); return StatusUnknown( StrCat("Only send ", wrote, " of ", headers.size())); } } return StatusOk(); } virtual googleapis::util::Status AddHeader(const string& name, const string& value) { headers_.push_back(std::make_pair(name, value)); return StatusOk(); } virtual googleapis::util::Status AddCookie(const string& name, const string& value) { cookies_.push_back(StrCat(name, "=", value)); return StatusOk(); } private: struct mg_connection* connection_; std::vector<std::pair<string, string> > headers_; std::vector<string> cookies_; }; // TODO(user): 20130626 // This doesnt read the post data, but there isnt really an // interface to get at it anyway. The current interface is only // intended to suppport OAuth 2.0 redirects, which GET a redirect. class MongooseRequest : public WebServerRequest { public: MongooseRequest(const struct mg_request_info* request_info, struct mg_connection* connection) : WebServerRequest( request_info->request_method, OriginalUri(request_info), new MongooseResponse(connection)), request_info_(request_info) { } virtual ~MongooseRequest() {} virtual bool GetCookieValue(const char* key, string* value) const { char local_storage[1 << 8]; char* buffer = local_storage; MongooseResponse* webserver_response = static_cast<MongooseResponse*>(response()); const char* cookies = mg_get_header(webserver_response->connection(), "Cookie"); int result = mg_get_cookie(cookies, key, buffer, sizeof(local_storage)); size_t size = 0; std::unique_ptr<char[]> heap_storage; if (result == -2) { heap_storage.reset(new char[size]); buffer = heap_storage.get(); result = mg_get_cookie(cookies, key, buffer, size); } if (result >= 0) { value->assign(buffer, result); return true; } else if (result < 2) { LOG(ERROR) << "cookie " << key << " is bigger than " << size << " bytes."; } return false; } virtual bool GetHeaderValue(const char* key, string* value) const { for (int i = 0; i < request_info_->num_headers; ++i) { if (strcmp(key, request_info_->http_headers[i].name) == 0) { *value = request_info_->http_headers[i].value; return true; } } return false; } private: const struct mg_request_info* request_info_; DISALLOW_COPY_AND_ASSIGN(MongooseRequest); }; const char MongooseWebServer::ACCESS_LOG_FILE[] = "access_log_file"; const char MongooseWebServer::DOCUMENT_ROOT[] = "document_root"; const char MongooseWebServer::ENABLE_KEEP_ALIVE[] = "enable_keep_alive"; const char MongooseWebServer::ERROR_LOG_FILE[] = "error_log_file"; const char MongooseWebServer::LISTENING_PORTS[] = "listening_ports"; const char MongooseWebServer::NUM_THREADS[] = "num_threads"; const char MongooseWebServer::REQUEST_TIMEOUT_MS[] = "request_timeout_ms"; const char MongooseWebServer::SSL_CERTIFICATE[] = "ssl_certificate"; int MongooseWebServer::BeginRequestHandler(struct mg_connection* connection) { const struct mg_request_info* request_info = mg_get_request_info(connection); MongooseWebServer* server = static_cast<MongooseWebServer*>(request_info->user_data); MongooseRequest request(request_info, connection); VLOG(1) << "Got " << request.parsed_url().url() << " " << request.method(); googleapis::util::Status status = server->DoHandleRequest(&request); VLOG(1) << "Completed " << request.parsed_url().url(); return status.ok(); // We sent a reply. } MongooseWebServer::MongooseWebServer(int port) : AbstractWebServer(port), kSslCertificateOption(SSL_CERTIFICATE), mg_context_(NULL) { memset(&callbacks_, 0, sizeof(callbacks_)); callbacks_.begin_request = BeginRequestHandler; } MongooseWebServer::~MongooseWebServer() { if (mg_context_) { Shutdown(); } } string MongooseWebServer::url_protocol() const { return use_ssl() ? "https" : "http"; } util::Status MongooseWebServer::DoStartup() { string port_str = SimpleItoa(port()); const string kPortOption = LISTENING_PORTS; string port_option = mongoose_option(kPortOption); if (!port_option.empty() && port_option != port_str) { return StatusFailedPrecondition("Inconsistent port and LISTENING_PORTS"); } options_.insert(std::make_pair(kPortOption, port_str)); if (!use_ssl()) { LOG(WARNING) << "Starting embedded MicroHttpd webserver without SSL"; } std::unique_ptr<const char* []> options( new const char*[2 * options_.size() + 1]); const char** next_option_ptr = options.get(); for (std::map<string, string>::const_iterator it = options_.begin(); it != options_.end(); ++it, next_option_ptr += 2) { next_option_ptr[0] = it->first.c_str(); next_option_ptr[1] = it->second.c_str(); } *next_option_ptr = NULL; mg_context_ = mg_start(&callbacks_, this, options.get()); if (mg_context_) { return googleapis::util::Status(); } else { return googleapis::util::Status(util::error::UNKNOWN, "Could not start Mongoose"); } } void MongooseWebServer::DoShutdown() { if (mg_context_) { mg_stop(mg_context_); mg_context_ = NULL; } } } // namespace client } // namespace googleapis <file_sep>/service_apis/youtube/google/youtube_api/promoted_item.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_PROMOTED_ITEM_H_ #define GOOGLE_YOUTUBE_API_PROMOTED_ITEM_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/invideo_timing.h" #include "google/youtube_api/promoted_item_id.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Describes a single promoted item. * * @ingroup DataObject */ class PromotedItem : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static PromotedItem* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit PromotedItem(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit PromotedItem(Json::Value* storage); /** * Standard destructor. */ virtual ~PromotedItem(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::PromotedItem</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::PromotedItem"); } /** * Determine if the '<code>customMessage</code>' attribute was set. * * @return true if the '<code>customMessage</code>' attribute was set. */ bool has_custom_message() const { return Storage().isMember("customMessage"); } /** * Clears the '<code>customMessage</code>' attribute. */ void clear_custom_message() { MutableStorage()->removeMember("customMessage"); } /** * Get the value of the '<code>customMessage</code>' attribute. */ const StringPiece get_custom_message() const { const Json::Value& v = Storage("customMessage"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>customMessage</code>' attribute. * * A custom message to display for this promotion. This field is currently * ignored unless the promoted item is a website. * * @param[in] value The new value. */ void set_custom_message(const StringPiece& value) { *MutableStorage("customMessage") = value.data(); } /** * Determine if the '<code>id</code>' attribute was set. * * @return true if the '<code>id</code>' attribute was set. */ bool has_id() const { return Storage().isMember("id"); } /** * Clears the '<code>id</code>' attribute. */ void clear_id() { MutableStorage()->removeMember("id"); } /** * Get a reference to the value of the '<code>id</code>' attribute. */ const PromotedItemId get_id() const; /** * Gets a reference to a mutable value of the '<code>id</code>' property. * * Identifies the promoted item. * * @return The result can be modified to change the attribute value. */ PromotedItemId mutable_id(); /** * Determine if the '<code>promotedByContentOwner</code>' attribute was set. * * @return true if the '<code>promotedByContentOwner</code>' attribute was * set. */ bool has_promoted_by_content_owner() const { return Storage().isMember("promotedByContentOwner"); } /** * Clears the '<code>promotedByContentOwner</code>' attribute. */ void clear_promoted_by_content_owner() { MutableStorage()->removeMember("promotedByContentOwner"); } /** * Get the value of the '<code>promotedByContentOwner</code>' attribute. */ bool get_promoted_by_content_owner() const { const Json::Value& storage = Storage("promotedByContentOwner"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>promotedByContentOwner</code>' attribute. * * If true, the content owner's name will be used when displaying the * promotion. This field can only be set when the update is made on behalf of * the content owner. * * @param[in] value The new value. */ void set_promoted_by_content_owner(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("promotedByContentOwner")); } /** * Determine if the '<code>timing</code>' attribute was set. * * @return true if the '<code>timing</code>' attribute was set. */ bool has_timing() const { return Storage().isMember("timing"); } /** * Clears the '<code>timing</code>' attribute. */ void clear_timing() { MutableStorage()->removeMember("timing"); } /** * Get a reference to the value of the '<code>timing</code>' attribute. */ const InvideoTiming get_timing() const; /** * Gets a reference to a mutable value of the '<code>timing</code>' property. * * The temporal position within the video where the promoted item will be * displayed. If present, it overrides the default timing. * * @return The result can be modified to change the attribute value. */ InvideoTiming mutable_timing(); private: void operator=(const PromotedItem&); }; // PromotedItem } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_PROMOTED_ITEM_H_ <file_sep>/src/samples/abstract_webserver_login_flow.h /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #ifndef GOOGLEAPIS_SAMPLES_ABSTRACT_WEBSERVER_LOGIN_FLOW_H_ #define GOOGLEAPIS_SAMPLES_ABSTRACT_WEBSERVER_LOGIN_FLOW_H_ #include <memory> #include <string> using std::string; #include "googleapis/client/auth/oauth2_pending_authorizations.h" #include "samples/abstract_login_flow.h" #include "googleapis/client/util/status.h" #include "googleapis/base/callback.h" #include "googleapis/base/macros.h" namespace googleapis { namespace client { class OAuth2AuthorizationFlow; class OAuth2Credential; } // namespace client namespace sample { using client::WebServerRequest; using client::WebServerResponse; /* * Component that manages obtaining credentials for user http sessions. * @ingroup Samples * * This class is just for experimenting and illustrative purposes. * Often it is simpler and perhaps more desirable to use something like * the Google+ javascript button (https://developers.google.com/+/web/signin/). * * Unlike the javascript button component, this mechanism is purely server * side code without any use of javascript. * * The class is thread-safe for managing concurrent login flows for different * users. * * Call InitiateAuthorizationFlow to initiate a flow. * This is usualy from an action on the page returned by * DoRespondWithLoginPage. * * Despite the name, this class is still abstract leaving the following * methods for managing user credetials and procuring page content. * DoReceiveCredentialForCookieId * DoGetCredentialForCookieId * DoRespondWithWelcomePage * DoRespondWithNotLoggedInPage * DoRespondWithLoginErrorPage */ class AbstractWebServerLoginFlow : public AbstractLoginFlow { public: /* * @param[in] RequestData The request received when resolved. * @return ok or reason for failure. */ typedef ResultCallback1< googleapis::util::Status, WebServerRequest*> PendingAuthorizationHandler; /* * Standard constructor. * * @param[in] cookie_name The name of the cookie to use for the cookie_id. * @param[in] flow The flow for talking to the OAuth 2.0 server when we * need to exchange an authorization code for access token. * @param[in] notifier The injected callback for pulling out the access codes * that we obtain for different users. */ AbstractWebServerLoginFlow(const string& cookie_name, const string& redirect_name, client::OAuth2AuthorizationFlow* flow); /* * Standard destructor. */ virtual ~AbstractWebServerLoginFlow(); protected: /* * This callback is used to resolve the requests from the OAuth 2.0 server * that gives us the authentication codes (or responses) that we asked for. */ virtual googleapis::util::Status DoHandleAccessTokenUrl(WebServerRequest* request); private: /* * Store of pending authorizations so we can correlate the tokens back * to their credentials. */ std::unique_ptr<client::OAuth2PendingAuthorizations< PendingAuthorizationHandler> > pending_; virtual googleapis::util::Status DoInitiateAuthorizationFlow( WebServerRequest* request, const string& redirect_url); /* * AbstractWebServer handler that gets access tokens for authorization codes. * * This is used as a callback. * * @param[in] cookie_id this is typically curried into the callback. * @param[in] want_url to redirect to is typically curried as well. * * @param[in] request_data is the inbound request we're receiving * that contains the authorization code. * * @return ok or reason for failure. */ googleapis::util::Status ReceiveAuthorizationCode( const string& cookie_id, const string& want_url, WebServerRequest* request); DISALLOW_COPY_AND_ASSIGN(AbstractWebServerLoginFlow); }; } // namespace sample } // namespace googleapis #endif // GOOGLEAPIS_SAMPLES_ABSTRACT_WEBSERVER_LOGIN_FLOW_H_ <file_sep>/service_apis/youtube/google/youtube_api/invideo_promotion.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_INVIDEO_PROMOTION_H_ #define GOOGLE_YOUTUBE_API_INVIDEO_PROMOTION_H_ #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/invideo_position.h" #include "google/youtube_api/invideo_timing.h" #include "google/youtube_api/promoted_item.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Describes an invideo promotion campaign consisting of multiple promoted * items. A campaign belongs to a single channel_id. * * @ingroup DataObject */ class InvideoPromotion : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static InvideoPromotion* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit InvideoPromotion(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit InvideoPromotion(Json::Value* storage); /** * Standard destructor. */ virtual ~InvideoPromotion(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::InvideoPromotion</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::InvideoPromotion"); } /** * Determine if the '<code>defaultTiming</code>' attribute was set. * * @return true if the '<code>defaultTiming</code>' attribute was set. */ bool has_default_timing() const { return Storage().isMember("defaultTiming"); } /** * Clears the '<code>defaultTiming</code>' attribute. */ void clear_default_timing() { MutableStorage()->removeMember("defaultTiming"); } /** * Get a reference to the value of the '<code>defaultTiming</code>' attribute. */ const InvideoTiming get_default_timing() const; /** * Gets a reference to a mutable value of the '<code>defaultTiming</code>' * property. * * The default temporal position within the video where the promoted item will * be displayed. Can be overriden by more specific timing in the item. * * @return The result can be modified to change the attribute value. */ InvideoTiming mutable_defaultTiming(); /** * Determine if the '<code>items</code>' attribute was set. * * @return true if the '<code>items</code>' attribute was set. */ bool has_items() const { return Storage().isMember("items"); } /** * Clears the '<code>items</code>' attribute. */ void clear_items() { MutableStorage()->removeMember("items"); } /** * Get a reference to the value of the '<code>items</code>' attribute. */ const client::JsonCppArray<PromotedItem > get_items() const; /** * Gets a reference to a mutable value of the '<code>items</code>' property. * * List of promoted items in decreasing priority. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<PromotedItem > mutable_items(); /** * Determine if the '<code>position</code>' attribute was set. * * @return true if the '<code>position</code>' attribute was set. */ bool has_position() const { return Storage().isMember("position"); } /** * Clears the '<code>position</code>' attribute. */ void clear_position() { MutableStorage()->removeMember("position"); } /** * Get a reference to the value of the '<code>position</code>' attribute. */ const InvideoPosition get_position() const; /** * Gets a reference to a mutable value of the '<code>position</code>' * property. * * The spatial position within the video where the promoted item will be * displayed. * * @return The result can be modified to change the attribute value. */ InvideoPosition mutable_position(); /** * Determine if the '<code>useSmartTiming</code>' attribute was set. * * @return true if the '<code>useSmartTiming</code>' attribute was set. */ bool has_use_smart_timing() const { return Storage().isMember("useSmartTiming"); } /** * Clears the '<code>useSmartTiming</code>' attribute. */ void clear_use_smart_timing() { MutableStorage()->removeMember("useSmartTiming"); } /** * Get the value of the '<code>useSmartTiming</code>' attribute. */ bool get_use_smart_timing() const { const Json::Value& storage = Storage("useSmartTiming"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>useSmartTiming</code>' attribute. * * Indicates whether the channel's promotional campaign uses "smart timing." * This feature attempts to show promotions at a point in the video when they * are more likely to be clicked and less likely to disrupt the viewing * experience. This feature also picks up a single promotion to show on each * video. * * @param[in] value The new value. */ void set_use_smart_timing(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("useSmartTiming")); } private: void operator=(const InvideoPromotion&); }; // InvideoPromotion } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_INVIDEO_PROMOTION_H_ <file_sep>/service_apis/drive/google/drive_api/revision.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Drive API (drive/v2) // Generated from: // Version: v2 // Revision: 20170512 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_DRIVE_API_REVISION_H_ #define GOOGLE_DRIVE_API_REVISION_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/drive_api/user.h" namespace Json { class Value; } // namespace Json namespace google_drive_api { using namespace googleapis; /** * A revision of a file. * * @ingroup DataObject */ class Revision : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static Revision* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Revision(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Revision(Json::Value* storage); /** * Standard destructor. */ virtual ~Revision(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::Revision</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::Revision"); } /** * Determine if the '<code>downloadUrl</code>' attribute was set. * * @return true if the '<code>downloadUrl</code>' attribute was set. */ bool has_download_url() const { return Storage().isMember("downloadUrl"); } /** * Clears the '<code>downloadUrl</code>' attribute. */ void clear_download_url() { MutableStorage()->removeMember("downloadUrl"); } /** * Get the value of the '<code>downloadUrl</code>' attribute. */ const StringPiece get_download_url() const { const Json::Value& v = Storage("downloadUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>downloadUrl</code>' attribute. * * Short term download URL for the file. This will only be populated on files * with content stored in Drive. * * @param[in] value The new value. */ void set_download_url(const StringPiece& value) { *MutableStorage("downloadUrl") = value.data(); } /** * Determine if the '<code>etag</code>' attribute was set. * * @return true if the '<code>etag</code>' attribute was set. */ bool has_etag() const { return Storage().isMember("etag"); } /** * Clears the '<code>etag</code>' attribute. */ void clear_etag() { MutableStorage()->removeMember("etag"); } /** * Get the value of the '<code>etag</code>' attribute. */ const StringPiece get_etag() const { const Json::Value& v = Storage("etag"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>etag</code>' attribute. * * The ETag of the revision. * * @param[in] value The new value. */ void set_etag(const StringPiece& value) { *MutableStorage("etag") = value.data(); } /** * Determine if the '<code>exportLinks</code>' attribute was set. * * @return true if the '<code>exportLinks</code>' attribute was set. */ bool has_export_links() const { return Storage().isMember("exportLinks"); } /** * Clears the '<code>exportLinks</code>' attribute. */ void clear_export_links() { MutableStorage()->removeMember("exportLinks"); } /** * Get a reference to the value of the '<code>exportLinks</code>' attribute. */ const client::JsonCppAssociativeArray<string > get_export_links() const { const Json::Value& storage = Storage("exportLinks"); return client::JsonValueToCppValueHelper<client::JsonCppAssociativeArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>exportLinks</code>' * property. * * Links for exporting Google Docs to specific formats. * * @return The result can be modified to change the attribute value. */ client::JsonCppAssociativeArray<string > mutable_exportLinks() { Json::Value* storage = MutableStorage("exportLinks"); return client::JsonValueToMutableCppValueHelper<client::JsonCppAssociativeArray<string > >(storage); } /** * Determine if the '<code>fileSize</code>' attribute was set. * * @return true if the '<code>fileSize</code>' attribute was set. */ bool has_file_size() const { return Storage().isMember("fileSize"); } /** * Clears the '<code>fileSize</code>' attribute. */ void clear_file_size() { MutableStorage()->removeMember("fileSize"); } /** * Get the value of the '<code>fileSize</code>' attribute. */ int64 get_file_size() const { const Json::Value& storage = Storage("fileSize"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>fileSize</code>' attribute. * * The size of the revision in bytes. This will only be populated on files * with content stored in Drive. * * @param[in] value The new value. */ void set_file_size(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("fileSize")); } /** * Determine if the '<code>id</code>' attribute was set. * * @return true if the '<code>id</code>' attribute was set. */ bool has_id() const { return Storage().isMember("id"); } /** * Clears the '<code>id</code>' attribute. */ void clear_id() { MutableStorage()->removeMember("id"); } /** * Get the value of the '<code>id</code>' attribute. */ const StringPiece get_id() const { const Json::Value& v = Storage("id"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>id</code>' attribute. * * The ID of the revision. * * @param[in] value The new value. */ void set_id(const StringPiece& value) { *MutableStorage("id") = value.data(); } /** * Determine if the '<code>kind</code>' attribute was set. * * @return true if the '<code>kind</code>' attribute was set. */ bool has_kind() const { return Storage().isMember("kind"); } /** * Clears the '<code>kind</code>' attribute. */ void clear_kind() { MutableStorage()->removeMember("kind"); } /** * Get the value of the '<code>kind</code>' attribute. */ const StringPiece get_kind() const { const Json::Value& v = Storage("kind"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kind</code>' attribute. * * This is always drive#revision. * * @param[in] value The new value. */ void set_kind(const StringPiece& value) { *MutableStorage("kind") = value.data(); } /** * Determine if the '<code>lastModifyingUser</code>' attribute was set. * * @return true if the '<code>lastModifyingUser</code>' attribute was set. */ bool has_last_modifying_user() const { return Storage().isMember("lastModifyingUser"); } /** * Clears the '<code>lastModifyingUser</code>' attribute. */ void clear_last_modifying_user() { MutableStorage()->removeMember("lastModifyingUser"); } /** * Get a reference to the value of the '<code>lastModifyingUser</code>' * attribute. */ const User get_last_modifying_user() const; /** * Gets a reference to a mutable value of the '<code>lastModifyingUser</code>' * property. * * The last user to modify this revision. * * @return The result can be modified to change the attribute value. */ User mutable_lastModifyingUser(); /** * Determine if the '<code>lastModifyingUserName</code>' attribute was set. * * @return true if the '<code>lastModifyingUserName</code>' attribute was set. */ bool has_last_modifying_user_name() const { return Storage().isMember("lastModifyingUserName"); } /** * Clears the '<code>lastModifyingUserName</code>' attribute. */ void clear_last_modifying_user_name() { MutableStorage()->removeMember("lastModifyingUserName"); } /** * Get the value of the '<code>lastModifyingUserName</code>' attribute. */ const StringPiece get_last_modifying_user_name() const { const Json::Value& v = Storage("lastModifyingUserName"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>lastModifyingUserName</code>' attribute. * * Name of the last user to modify this revision. * * @param[in] value The new value. */ void set_last_modifying_user_name(const StringPiece& value) { *MutableStorage("lastModifyingUserName") = value.data(); } /** * Determine if the '<code>md5Checksum</code>' attribute was set. * * @return true if the '<code>md5Checksum</code>' attribute was set. */ bool has_md5_checksum() const { return Storage().isMember("md5Checksum"); } /** * Clears the '<code>md5Checksum</code>' attribute. */ void clear_md5_checksum() { MutableStorage()->removeMember("md5Checksum"); } /** * Get the value of the '<code>md5Checksum</code>' attribute. */ const StringPiece get_md5_checksum() const { const Json::Value& v = Storage("md5Checksum"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>md5Checksum</code>' attribute. * * An MD5 checksum for the content of this revision. This will only be * populated on files with content stored in Drive. * * @param[in] value The new value. */ void set_md5_checksum(const StringPiece& value) { *MutableStorage("md5Checksum") = value.data(); } /** * Determine if the '<code>mimeType</code>' attribute was set. * * @return true if the '<code>mimeType</code>' attribute was set. */ bool has_mime_type() const { return Storage().isMember("mimeType"); } /** * Clears the '<code>mimeType</code>' attribute. */ void clear_mime_type() { MutableStorage()->removeMember("mimeType"); } /** * Get the value of the '<code>mimeType</code>' attribute. */ const StringPiece get_mime_type() const { const Json::Value& v = Storage("mimeType"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>mimeType</code>' attribute. * * The MIME type of the revision. * * @param[in] value The new value. */ void set_mime_type(const StringPiece& value) { *MutableStorage("mimeType") = value.data(); } /** * Determine if the '<code>modifiedDate</code>' attribute was set. * * @return true if the '<code>modifiedDate</code>' attribute was set. */ bool has_modified_date() const { return Storage().isMember("modifiedDate"); } /** * Clears the '<code>modifiedDate</code>' attribute. */ void clear_modified_date() { MutableStorage()->removeMember("modifiedDate"); } /** * Get the value of the '<code>modifiedDate</code>' attribute. */ client::DateTime get_modified_date() const { const Json::Value& storage = Storage("modifiedDate"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>modifiedDate</code>' attribute. * * Last time this revision was modified (formatted RFC 3339 timestamp). * * @param[in] value The new value. */ void set_modified_date(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("modifiedDate")); } /** * Determine if the '<code>originalFilename</code>' attribute was set. * * @return true if the '<code>originalFilename</code>' attribute was set. */ bool has_original_filename() const { return Storage().isMember("originalFilename"); } /** * Clears the '<code>originalFilename</code>' attribute. */ void clear_original_filename() { MutableStorage()->removeMember("originalFilename"); } /** * Get the value of the '<code>originalFilename</code>' attribute. */ const StringPiece get_original_filename() const { const Json::Value& v = Storage("originalFilename"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>originalFilename</code>' attribute. * * The original filename when this revision was created. This will only be * populated on files with content stored in Drive. * * @param[in] value The new value. */ void set_original_filename(const StringPiece& value) { *MutableStorage("originalFilename") = value.data(); } /** * Determine if the '<code>pinned</code>' attribute was set. * * @return true if the '<code>pinned</code>' attribute was set. */ bool has_pinned() const { return Storage().isMember("pinned"); } /** * Clears the '<code>pinned</code>' attribute. */ void clear_pinned() { MutableStorage()->removeMember("pinned"); } /** * Get the value of the '<code>pinned</code>' attribute. */ bool get_pinned() const { const Json::Value& storage = Storage("pinned"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>pinned</code>' attribute. * * Whether this revision is pinned to prevent automatic purging. This will * only be populated and can only be modified on files with content stored in * Drive which are not Google Docs. Revisions can also be pinned when they are * created through the drive.files.insert/update/copy by using the pinned * query parameter. * * @param[in] value The new value. */ void set_pinned(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("pinned")); } /** * Determine if the '<code>publishAuto</code>' attribute was set. * * @return true if the '<code>publishAuto</code>' attribute was set. */ bool has_publish_auto() const { return Storage().isMember("publishAuto"); } /** * Clears the '<code>publishAuto</code>' attribute. */ void clear_publish_auto() { MutableStorage()->removeMember("publishAuto"); } /** * Get the value of the '<code>publishAuto</code>' attribute. */ bool get_publish_auto() const { const Json::Value& storage = Storage("publishAuto"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>publishAuto</code>' attribute. * * Whether subsequent revisions will be automatically republished. This is * only populated and can only be modified for Google Docs. * * @param[in] value The new value. */ void set_publish_auto(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("publishAuto")); } /** * Determine if the '<code>published</code>' attribute was set. * * @return true if the '<code>published</code>' attribute was set. */ bool has_published() const { return Storage().isMember("published"); } /** * Clears the '<code>published</code>' attribute. */ void clear_published() { MutableStorage()->removeMember("published"); } /** * Get the value of the '<code>published</code>' attribute. */ bool get_published() const { const Json::Value& storage = Storage("published"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>published</code>' attribute. * * Whether this revision is published. This is only populated and can only be * modified for Google Docs. * * @param[in] value The new value. */ void set_published(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("published")); } /** * Determine if the '<code>publishedLink</code>' attribute was set. * * @return true if the '<code>publishedLink</code>' attribute was set. */ bool has_published_link() const { return Storage().isMember("publishedLink"); } /** * Clears the '<code>publishedLink</code>' attribute. */ void clear_published_link() { MutableStorage()->removeMember("publishedLink"); } /** * Get the value of the '<code>publishedLink</code>' attribute. */ const StringPiece get_published_link() const { const Json::Value& v = Storage("publishedLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>publishedLink</code>' attribute. * * A link to the published revision. * * @param[in] value The new value. */ void set_published_link(const StringPiece& value) { *MutableStorage("publishedLink") = value.data(); } /** * Determine if the '<code>publishedOutsideDomain</code>' attribute was set. * * @return true if the '<code>publishedOutsideDomain</code>' attribute was * set. */ bool has_published_outside_domain() const { return Storage().isMember("publishedOutsideDomain"); } /** * Clears the '<code>publishedOutsideDomain</code>' attribute. */ void clear_published_outside_domain() { MutableStorage()->removeMember("publishedOutsideDomain"); } /** * Get the value of the '<code>publishedOutsideDomain</code>' attribute. */ bool get_published_outside_domain() const { const Json::Value& storage = Storage("publishedOutsideDomain"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>publishedOutsideDomain</code>' attribute. * * Whether this revision is published outside the domain. This is only * populated and can only be modified for Google Docs. * * @param[in] value The new value. */ void set_published_outside_domain(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("publishedOutsideDomain")); } /** * Determine if the '<code>selfLink</code>' attribute was set. * * @return true if the '<code>selfLink</code>' attribute was set. */ bool has_self_link() const { return Storage().isMember("selfLink"); } /** * Clears the '<code>selfLink</code>' attribute. */ void clear_self_link() { MutableStorage()->removeMember("selfLink"); } /** * Get the value of the '<code>selfLink</code>' attribute. */ const StringPiece get_self_link() const { const Json::Value& v = Storage("selfLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>selfLink</code>' attribute. * * A link back to this revision. * * @param[in] value The new value. */ void set_self_link(const StringPiece& value) { *MutableStorage("selfLink") = value.data(); } private: void operator=(const Revision&); }; // Revision } // namespace google_drive_api #endif // GOOGLE_DRIVE_API_REVISION_H_ <file_sep>/src/googleapis/client/auth/oauth2_authorization.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <fstream> #include <memory> #include <sstream> #include <string> using std::string; #include <vector> #include "googleapis/base/callback.h" #include <glog/logging.h> #include "googleapis/base/mutex.h" #include "googleapis/client/auth/credential_store.h" #include "googleapis/client/auth/oauth2_authorization.h" #include "googleapis/client/data/data_reader.h" #include "googleapis/client/transport/http_request.h" #include "googleapis/client/transport/http_response.h" #include "googleapis/client/transport/http_transport.h" #include "googleapis/client/transport/http_types.h" #include "googleapis/strings/case.h" #include "googleapis/client/util/date_time.h" #include "googleapis/client/util/escaping.h" #include "googleapis/client/util/status.h" #include "googleapis/client/util/uri_utils.h" // Note we are explicitly using jsoncpp here as an implementation detail. // We are intentionally not using the jsoncpp_data package introduced by // this package. Two reasons for this // 1) This is an implementation detail not exposed externally // 2) I want to keep JsonCppData decoupled so I can easily replace the // data model. Currently JsonCppData is introduced by the code generator // and not by the core runtime library. #include <json/reader.h> #include <json/value.h> #include "googleapis/strings/join.h" #include "googleapis/strings/numbers.h" #include "googleapis/strings/split.h" #include "googleapis/strings/strcat.h" #include "googleapis/strings/stringpiece.h" #include "googleapis/strings/util.h" namespace googleapis { namespace { using client::StatusInvalidArgument; using client::StatusOk; using client::StatusUnknown; const char kDefaultAuthUri_[] = "https://accounts.google.com/o/oauth2/auth"; const char kDefaultTokenUri_[] = "https://accounts.google.com/o/oauth2/token"; const char kDefaultRevokeUri_[] = "https://accounts.google.com/o/oauth2/revoke"; } // anonymous namespace namespace client { void OAuth2AuthorizationFlow::ResetCredentialStore(CredentialStore* store) { credential_store_.reset(store); } class OAuth2AuthorizationFlow::SimpleJsonData { public: SimpleJsonData() {} googleapis::util::Status Init(const string& json); string InitFromContainer(const string& json); bool GetString(const char* field, string* value) const; bool GetScalar(const char* field, int* value) const; bool GetBool(const char* field, bool* value) const; bool GetFirstArrayElement(const char* field, string* value) const; private: mutable Json::Value json_; }; util::Status OAuth2AuthorizationFlow::SimpleJsonData::Init( const string& json) { Json::Reader reader; std::istringstream stream(json); if (!reader.parse(stream, json_)) { googleapis::util::Status status(StatusInvalidArgument("Invalid JSON")); LOG(ERROR) << status.error_message(); return status; } return StatusOk(); } string OAuth2AuthorizationFlow::SimpleJsonData::InitFromContainer( const string& json) { if (!Init(json).ok() || json_.begin() == json_.end()) { return ""; } string name = json_.begin().key().asString(); json_ = *json_.begin(); return name; } bool OAuth2AuthorizationFlow::SimpleJsonData::GetString( const char* field_name, string* value) const { if (!json_.isMember(field_name)) return false; *value = json_[field_name].asString(); return true; } bool OAuth2AuthorizationFlow::SimpleJsonData::GetScalar( const char* field_name, int* value) const { if (!json_.isMember(field_name)) return false; *value = json_[field_name].asInt(); return true; } bool OAuth2AuthorizationFlow::SimpleJsonData::GetBool( const char* field_name, bool* value) const { if (!json_.isMember(field_name)) return false; *value = json_[field_name].asBool(); return true; } bool OAuth2AuthorizationFlow::SimpleJsonData::GetFirstArrayElement( const char* field_name, string* value) const { if (!json_.isMember(field_name)) return false; Json::Value array = json_[field_name]; if (array.size() == 0) return false; *value = (*array.begin()).asString(); return true; } void OAuth2AuthorizationFlow::AppendJsonStringAttribute( string* to, const string& sep, const string& name, const string& value) { StrAppend(to, sep, "\"", name, "\":\"", value, "\""); } void OAuth2AuthorizationFlow::AppendJsonScalarAttribute( string* to, const string& sep, const string& name, int value) { StrAppend(to, sep, "\"", name, "\":", value); } bool OAuth2AuthorizationFlow::GetStringAttribute( const SimpleJsonData* data, const char* key, string* value) { return data->GetString(key, value); } const char OAuth2AuthorizationFlow::kOutOfBandUrl[] = "urn:ietf:wg:oauth:2.0:oob"; const char OAuth2AuthorizationFlow::kGoogleAccountsOauth2Url[] = "https://accounts.google.com/o/oauth2"; OAuth2ClientSpec::OAuth2ClientSpec() : auth_uri_(kDefaultAuthUri_), token_uri_(kDefaultTokenUri_), revoke_uri_(kDefaultRevokeUri_) { } OAuth2ClientSpec::~OAuth2ClientSpec() { } const char OAuth2Credential::kOAuth2CredentialType[] = "OAuth2"; OAuth2Credential::OAuth2Credential() : flow_(NULL), email_verified_(false) { // If we dont know an expiration then assume it never will. expiration_timestamp_secs_.set(kint64max); } OAuth2Credential::~OAuth2Credential() { } const string OAuth2Credential::type() const { return kOAuth2CredentialType; } void OAuth2Credential::Clear() { access_token_.clear(); refresh_token_.clear(); expiration_timestamp_secs_.set(kint64max); email_.clear(); email_verified_ = false; } util::Status OAuth2Credential::Refresh() { if (!flow_) { return StatusFailedPrecondition("No flow bound."); } return flow_->PerformRefreshToken(OAuth2RequestOptions(), this); } void OAuth2Credential::RefreshAsync(Callback1<util::Status>* callback) { if (!flow_) { callback->Run(StatusFailedPrecondition("No flow bound.")); return; } flow_->PerformRefreshTokenAsync(OAuth2RequestOptions(), this, callback); } util::Status OAuth2Credential::Load(DataReader* reader) { Clear(); return Update(reader); } util::Status OAuth2Credential::Update(DataReader* reader) { string json = reader->RemainderToString(); if (reader->error()) { googleapis::util::Status status(util::error::UNKNOWN, "Invalid credential"); LOG(ERROR) << status.error_message(); return status; } return UpdateFromString(json); } DataReader* OAuth2Credential::MakeDataReader() const { string refresh_token = refresh_token_.as_string(); string access_token = access_token_.as_string(); int64 expires_at = expiration_timestamp_secs_.get(); string json = "{"; const char* sep = ""; if (!access_token.empty()) { OAuth2AuthorizationFlow::AppendJsonStringAttribute( &json, sep, "access_token", access_token); sep = ","; } if (!refresh_token.empty()) { OAuth2AuthorizationFlow::AppendJsonStringAttribute( &json, sep, "refresh_token", refresh_token); sep = ","; } if (expires_at != kint64max) { OAuth2AuthorizationFlow::AppendJsonStringAttribute( &json, sep, "expires_at", SimpleItoa(expires_at)); sep = ","; } if (!email_.empty()) { OAuth2AuthorizationFlow::AppendJsonStringAttribute( &json, sep, "email", email_); // OAuth returns this bool as "true"/"false" string, not a bool. // We'll keep it that way too for consistency. OAuth2AuthorizationFlow::AppendJsonStringAttribute( &json, sep, "email_verified", email_verified_ ? "true" : "false"); } json.append("}"); return NewManagedInMemoryDataReader(json); } util::Status OAuth2Credential::AuthorizeRequest(HttpRequest* request) { if (!access_token_.empty()) { string bearer = "Bearer "; access_token_.AppendTo(&bearer); request->AddHeader(HttpRequest::HttpHeader_AUTHORIZATION, bearer); } return StatusOk(); } util::Status OAuth2Credential::UpdateFromString(const string& json) { OAuth2AuthorizationFlow::SimpleJsonData data; googleapis::util::Status status = data.Init(json); if (!status.ok()) return status; string str_value; int int_value; if (data.GetString("refresh_token", &str_value)) { VLOG(1) << "Updating refresh token"; refresh_token_.set(str_value); } if (data.GetString("access_token", &str_value)) { access_token_.set(str_value); VLOG(1) << "Updating access token"; } if (data.GetString("expires_at", &str_value) || data.GetString("exp", &str_value)) { int64 timestamp; if (!safe_strto64(str_value.c_str(), &timestamp)) { LOG(ERROR) << "Invalid timestamp=[" << str_value << "]"; } else { expiration_timestamp_secs_.set(timestamp); VLOG(1) << "Updating access token expiration"; } } else if (data.GetScalar("expires_in", &int_value)) { int64 now = DateTime().ToEpochTime(); int64 expiration = now + int_value; expiration_timestamp_secs_.set(expiration); VLOG(1) << "Updating access token expiration"; } if (data.GetString("email", &str_value)) { string bool_str; // Read this as a string because OAuth2 server returns it as // a true/false string. data.GetString("email_verified", &bool_str); email_ = str_value; email_verified_ = bool_str == "true"; } if (data.GetString("id_token", &str_value)) { // Extract additional stuff from the JWT claims. // We dont need to verify the signature since we already know // this is coming from the OAuth2 server and is secure with https. // see https://developers.google.com/accounts/docs/OAuth2Login // #validatinganidtoken int dot_positions[3]; int n_dots = 0; for (size_t i = 0; i < str_value.size(); ++i) { if (str_value[i] == '.') { dot_positions[n_dots] = i; ++n_dots; if (n_dots == 3) break; } } if (n_dots != 2) { return StatusUnknown("Invalid id_token attribute - not a JWT"); } string claims; const char *claims_start = str_value.data() + dot_positions[0] + 1; size_t claims_len = dot_positions[1] - dot_positions[0] - 1; if (!googleapis_util::Base64Unescape(claims_start, claims_len, &claims)) { return StatusUnknown("id_token claims not base-64 encoded"); } return UpdateFromString(claims); } return StatusOk(); } OAuth2AuthorizationFlow::OAuth2AuthorizationFlow(HttpTransport* transport) : check_email_(false), transport_(transport) { } OAuth2AuthorizationFlow::~OAuth2AuthorizationFlow() { } OAuth2Credential* OAuth2AuthorizationFlow::NewCredential() { OAuth2Credential* credential = new OAuth2Credential; credential->set_flow(this); return credential; } void OAuth2AuthorizationFlow::set_authorization_code_callback( AuthorizationCodeCallback* callback) { if (callback) callback->CheckIsRepeatable(); authorization_code_callback_.reset(callback); } util::Status OAuth2AuthorizationFlow::PerformExchangeAuthorizationCode( const string& authorization_code, const OAuth2RequestOptions& options, OAuth2Credential* credential) { if (authorization_code.empty()) { return StatusInvalidArgument("Missing authorization code"); } if (client_spec_.client_id().empty()) { return StatusFailedPrecondition("Missing client ID"); } if (client_spec_.client_secret().empty()) { return StatusFailedPrecondition("Missing client secret"); } const string redirect = options.redirect_uri.empty() ? client_spec_.redirect_uri() : options.redirect_uri; string content = StrCat("code=", EscapeForUrl(authorization_code), "&client_id=", EscapeForUrl(client_spec_.client_id()), "&client_secret=", EscapeForUrl(client_spec_.client_secret()), "&redirect_uri=", EscapeForUrl(redirect), "&grant_type=authorization_code"); std::unique_ptr<HttpRequest> request( transport_->NewHttpRequest(HttpRequest::POST)); if (options.timeout_ms > 0) { request->mutable_options()->set_timeout_ms(options.timeout_ms); } request->set_url(client_spec_.token_uri()); request->set_content_type(HttpRequest::ContentType_FORM_URL_ENCODED); request->set_content_reader(NewUnmanagedInMemoryDataReader(content)); googleapis::util::Status status = request->Execute(); if (status.ok()) { status = credential->Update(request->response()->body_reader()); if (status.ok() && check_email_ && !options.email.empty()) { if (options.email != credential->email()) { status = StatusUnknown( StrCat("Credential email address mismatch. Expected [", options.email, "] but got [", credential->email(), "]")); credential->Clear(); } } } return status; } util::Status OAuth2AuthorizationFlow::PerformRefreshToken( const OAuth2RequestOptions& options, OAuth2Credential* credential) { googleapis::util::Status tokenStatus = ValidateRefreshToken_(credential); if (!tokenStatus.ok()) { return tokenStatus; } std::unique_ptr<HttpRequest> request( ConstructRefreshTokenRequest_(options, credential)); googleapis::util::Status status = request->Execute(); if (status.ok()) { status = credential->Update(request->response()->body_reader()); } if (!status.ok()) { LOG(ERROR) << "Refresh failed with " << status.error_message(); } return status; } void OAuth2AuthorizationFlow::PerformRefreshTokenAsync( const OAuth2RequestOptions& options, OAuth2Credential* credential, Callback1<util::Status>* callback) { googleapis::util::Status status = ValidateRefreshToken_(credential); if (!status.ok()) { callback->Run(status); return; } HttpRequest* request = ConstructRefreshTokenRequest_(options, credential); HttpRequestCallback* cb = NewCallback(this, &OAuth2AuthorizationFlow::UpdateCredentialAsync, credential, callback); request->DestroyWhenDone(); request->ExecuteAsync(cb); } HttpRequest* OAuth2AuthorizationFlow::ConstructRefreshTokenRequest_( const OAuth2RequestOptions& options, OAuth2Credential* credential) { HttpRequest* request(transport_->NewHttpRequest(HttpRequest::POST)); if (options.timeout_ms > 0) { request->mutable_options()->set_timeout_ms(options.timeout_ms); } request->set_url(client_spec_.token_uri()); request->set_content_type(HttpRequest::ContentType_FORM_URL_ENCODED); string* content = BuildRefreshTokenContent_(credential); request->set_content_reader(NewManagedInMemoryDataReader(content)); return request; } util::Status OAuth2AuthorizationFlow::ValidateRefreshToken_( OAuth2Credential* credential) const { if (client_spec_.client_id().empty()) { return StatusFailedPrecondition("Missing client ID"); } if (client_spec_.client_secret().empty()) { return StatusFailedPrecondition("Missing client secret"); } if (credential->refresh_token().empty()) { return StatusInvalidArgument("Missing refresh token"); } return StatusOk(); } string* OAuth2AuthorizationFlow::BuildRefreshTokenContent_( OAuth2Credential* credential) { string* content = new string( StrCat("client_id=", client_spec_.client_id(), "&client_secret=", client_spec_.client_secret(), "&grant_type=refresh_token", "&refresh_token=")); credential->refresh_token().AppendTo(content); return content; } void OAuth2AuthorizationFlow::UpdateCredentialAsync( OAuth2Credential* credential, Callback1<util::Status>* callback, HttpRequest* request) { googleapis::util::Status status = request->response()->status(); if (status.ok()) { status = credential->Update(request->response()->body_reader()); } if (!status.ok()) { LOG(ERROR) << "Refresh failed with " << status.error_message(); } if (NULL != callback) { callback->Run(status); } } util::Status OAuth2AuthorizationFlow::PerformRevokeToken( bool access_token_only, OAuth2Credential* credential) { std::unique_ptr<HttpRequest> request( transport_->NewHttpRequest(HttpRequest::POST)); request->set_url(client_spec_.revoke_uri()); request->set_content_type(HttpRequest::ContentType_FORM_URL_ENCODED); ThreadsafeString* token = access_token_only ? credential->mutable_access_token() : credential->mutable_refresh_token(); string* content = new string("token="); token->AppendTo(content); request->set_content_reader(NewManagedInMemoryDataReader(content)); googleapis::util::Status status = request->Execute(); if (status.ok()) { token->set(""); } return status; } util::Status OAuth2AuthorizationFlow::RefreshCredentialWithOptions( const OAuth2RequestOptions& options, OAuth2Credential* credential) { string refresh_token = credential->refresh_token().as_string(); if (refresh_token.empty() && credential_store_.get()) { // If we dont have a refresh token, try reloading from the store. // This could because we havent yet loaded the credential. // If this fails, we'll just handle it as a first-time case. googleapis::util::Status status = credential_store_->InitCredential(options.email, credential); if (status.ok()) { if (check_email_ && credential->email() != options.email) { status = StatusUnknown( StrCat( "Stored credential email address mismatch. Expected [", options.email, "] but got [", credential->email(), "]")); credential->Clear(); } else if (credential->email().empty()) { credential->set_email(options.email, false); } if (status.ok()) { refresh_token = credential->refresh_token().as_string(); } } } // Default status is not ok, meaning we did not make any attempts yet. googleapis::util::Status refresh_status = StatusUnknown("Do not have authorization"); if (!refresh_token.empty()) { if (options.email != credential->email()) { string error = "Email does not match credential's email"; LOG(ERROR) << error; return StatusInvalidArgument(error); } // Maybe this will be ok, maybe not. If not we'll continue as if we // never had a refresh token in case it is invalid or revoked. refresh_status = PerformRefreshToken(options, credential); // Try executing this request. If it fails, we'll continue as if we // did not find the token. if (!refresh_status.ok()) { LOG(ERROR) << "Could not refresh existing credential: " << refresh_status.error_message() << "\n" << "Trying to obtain a new one instead."; } } if (refresh_status.ok()) { // Do nothing until common code below. } else if (!authorization_code_callback_.get()) { const char error[] = "No prompting mechanism provided to get authorization"; LOG(ERROR) << error; return StatusUnimplemented(error); } else { // If we still dont have a credential then we need to kick off // authorization again to get an access (and refresh) token. string auth_code; OAuth2RequestOptions actual_options = options; if (actual_options.scopes.empty()) { actual_options.scopes = default_scopes_; } if (actual_options.redirect_uri.empty()) { actual_options.redirect_uri = client_spec_.redirect_uri(); } googleapis::util::Status status = authorization_code_callback_->Run(actual_options, &auth_code); if (!status.ok()) return status; refresh_status = PerformExchangeAuthorizationCode(auth_code, options, credential); // TODO(user): 20130301 // Add an attribute to the flow where it will validate users. // If that's set then make another oauth2 call here to validate the user. // We'll need to add the oauth2 scope to the set of credentials so we // can make that oauth2 sevice call. } // Now that we have the request, execute it and write the result into the // credential store if successful. if (refresh_status.ok() && !options.email.empty()) { credential->set_email(options.email, false); if (credential_store_.get()) { // TODO(user): 20130301 // if we havent verified the email yet, then attempt to do so first. googleapis::util::Status status = credential_store_->Store(options.email, *credential); if (!status.ok()) { LOG(WARNING) << "Could not store credential: " << status.error_message(); } } } return refresh_status; } string OAuth2AuthorizationFlow::GenerateAuthorizationCodeRequestUrlWithOptions( const OAuth2RequestOptions& options) const { string default_redirect(client_spec_.redirect_uri()); string actual_scopes; string scopes = options.scopes.empty() ? default_scopes_ : options.scopes; if (check_email_ && !(scopes.find("email ") == 0) && scopes.find(" email") == string::npos) { // Add "email" scope if it isnt already present actual_scopes = StrCat("email ", scopes); scopes = actual_scopes; } const string redirect = options.redirect_uri.empty() ? client_spec_.redirect_uri() : options.redirect_uri; CHECK(!scopes.empty()); CHECK(!client_spec_.client_id().empty()) << "client_id not set"; return StrCat(client_spec_.auth_uri(), "?client_id=", EscapeForUrl(client_spec_.client_id()), "&redirect_uri=", EscapeForUrl(redirect), "&scope=", EscapeForUrl(scopes), "&response_type=code"); } // static string OAuth2AuthorizationFlow::JoinScopes( const std::vector<string>& scopes) { return strings::Join(scopes, " "); } // static OAuth2AuthorizationFlow* OAuth2AuthorizationFlow::MakeFlowFromClientSecretsPath( const string& path, HttpTransport* transport, googleapis::util::Status* status) { string json(std::istreambuf_iterator<char>(std::ifstream(path).rdbuf()), std::istreambuf_iterator<char>()); return MakeFlowFromClientSecretsJson(json, transport, status); } // static OAuth2AuthorizationFlow* OAuth2AuthorizationFlow::MakeFlowFromClientSecretsJson( const string& json, HttpTransport* transport, googleapis::util::Status* status) { std::unique_ptr<HttpTransport> transport_deleter(transport); if (!transport) { *status = StatusInvalidArgument("No transport instance provided"); return NULL; } SimpleJsonData data; string root_name = data.InitFromContainer(json); if (root_name.empty()) { *status = StatusInvalidArgument("Invalid JSON"); return NULL; } std::unique_ptr<OAuth2AuthorizationFlow> flow; if (StringCaseEqual(root_name, "installed")) { flow.reset( new OAuth2InstalledApplicationFlow(transport_deleter.release())); } else if (StringCaseEqual(root_name, "web")) { flow.reset(new OAuth2WebApplicationFlow(transport_deleter.release())); } else { *status = StatusInvalidArgument(StrCat("Unhandled OAuth2 flow=", root_name)); return NULL; } *status = flow->InitFromJsonData(&data); if (status->ok()) { return flow.release(); } return NULL; } util::Status OAuth2AuthorizationFlow::InitFromJson(const string& json) { SimpleJsonData data; string root_name = data.InitFromContainer(json); if (root_name.empty()) { return StatusInvalidArgument("Invalid JSON"); } return InitFromJsonData(&data); } util::Status OAuth2AuthorizationFlow::InitFromJsonData( const OAuth2AuthorizationFlow::SimpleJsonData* data) { OAuth2ClientSpec* spec = mutable_client_spec(); string value; if (data->GetString("client_id", &value)) { spec->set_client_id(value); } if (data->GetString("client_secret", &value)) { spec->set_client_secret(value); } if (data->GetString("auth_uri", &value)) { spec->set_auth_uri(value); } if (data->GetString("token_uri", &value)) { spec->set_token_uri(value); } if (data->GetFirstArrayElement("redirect_uris", &value)) { spec->set_redirect_uri(value); } return StatusOk(); } OAuth2InstalledApplicationFlow::OAuth2InstalledApplicationFlow( HttpTransport* transport) : OAuth2AuthorizationFlow(transport) { } OAuth2InstalledApplicationFlow::~OAuth2InstalledApplicationFlow() { } string OAuth2InstalledApplicationFlow::GenerateAuthorizationCodeRequestUrl( const string& scope) const { return OAuth2AuthorizationFlow::GenerateAuthorizationCodeRequestUrl(scope); } util::Status OAuth2InstalledApplicationFlow::InitFromJsonData( const OAuth2AuthorizationFlow::SimpleJsonData* data) { return OAuth2AuthorizationFlow::InitFromJsonData(data); } OAuth2WebApplicationFlow::OAuth2WebApplicationFlow( HttpTransport* transport) : OAuth2AuthorizationFlow(transport), offline_access_type_(false), force_approval_prompt_(false) { } OAuth2WebApplicationFlow::~OAuth2WebApplicationFlow() { } string OAuth2WebApplicationFlow::GenerateAuthorizationCodeRequestUrl( const string& scope) const { string url = OAuth2AuthorizationFlow::GenerateAuthorizationCodeRequestUrl(scope); if (force_approval_prompt_) { StrAppend(&url, "&approval_prompt=force"); } if (offline_access_type_) { StrAppend(&url, "&access_type=offline"); } return url; } util::Status OAuth2WebApplicationFlow::InitFromJsonData( const OAuth2AuthorizationFlow::SimpleJsonData* data) { googleapis::util::Status status = OAuth2AuthorizationFlow::InitFromJsonData(data); if (status.ok()) { string value; if (data->GetString("access_type", &value)) { offline_access_type_ = (value == "offline"); if (!offline_access_type_ && value != "online") { return StatusInvalidArgument( StrCat("Invalid access_type=", value)); } } if (data->GetString("approval_prompt", &value)) { force_approval_prompt_ = (value == "force"); if (!force_approval_prompt_ && value != "auto") { return StatusInvalidArgument( StrCat("Invalid approval_prompt=", value)); } } } return status; } void ThreadsafeString::set(const StringPiece& value) { MutexLock l(&mutex_); value_ = value.as_string(); } } // namespace client } // namespace googleapis <file_sep>/service_apis/drive/google/drive_api/about.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Drive API (drive/v2) // Generated from: // Version: v2 // Revision: 20170512 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_DRIVE_API_ABOUT_H_ #define GOOGLE_DRIVE_API_ABOUT_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/drive_api/user.h" namespace Json { class Value; } // namespace Json namespace google_drive_api { using namespace googleapis; /** * An item with user information and settings. * * @ingroup DataObject */ class About : public client::JsonCppData { public: /** * No description provided. * * @ingroup DataObject */ class AboutAdditionalRoleInfo : public client::JsonCppData { public: /** * No description provided. * * @ingroup DataObject */ class AboutAdditionalRoleInfoRoleSets : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static AboutAdditionalRoleInfoRoleSets* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutAdditionalRoleInfoRoleSets(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutAdditionalRoleInfoRoleSets(Json::Value* storage); /** * Standard destructor. */ virtual ~AboutAdditionalRoleInfoRoleSets(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::AboutAdditionalRoleInfoRoleSets</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::AboutAdditionalRoleInfoRoleSets"); } /** * Determine if the '<code>additionalRoles</code>' attribute was set. * * @return true if the '<code>additionalRoles</code>' attribute was set. */ bool has_additional_roles() const { return Storage().isMember("additionalRoles"); } /** * Clears the '<code>additionalRoles</code>' attribute. */ void clear_additional_roles() { MutableStorage()->removeMember("additionalRoles"); } /** * Get a reference to the value of the '<code>additionalRoles</code>' * attribute. */ const client::JsonCppArray<string > get_additional_roles() const { const Json::Value& storage = Storage("additionalRoles"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the * '<code>additionalRoles</code>' property. * * The supported additional roles with the primary role. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_additionalRoles() { Json::Value* storage = MutableStorage("additionalRoles"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>primaryRole</code>' attribute was set. * * @return true if the '<code>primaryRole</code>' attribute was set. */ bool has_primary_role() const { return Storage().isMember("primaryRole"); } /** * Clears the '<code>primaryRole</code>' attribute. */ void clear_primary_role() { MutableStorage()->removeMember("primaryRole"); } /** * Get the value of the '<code>primaryRole</code>' attribute. */ const StringPiece get_primary_role() const { const Json::Value& v = Storage("primaryRole"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>primaryRole</code>' attribute. * * A primary permission role. * * @param[in] value The new value. */ void set_primary_role(const StringPiece& value) { *MutableStorage("primaryRole") = value.data(); } private: void operator=(const AboutAdditionalRoleInfoRoleSets&); }; // AboutAdditionalRoleInfoRoleSets /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static AboutAdditionalRoleInfo* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutAdditionalRoleInfo(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutAdditionalRoleInfo(Json::Value* storage); /** * Standard destructor. */ virtual ~AboutAdditionalRoleInfo(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::AboutAdditionalRoleInfo</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::AboutAdditionalRoleInfo"); } /** * Determine if the '<code>roleSets</code>' attribute was set. * * @return true if the '<code>roleSets</code>' attribute was set. */ bool has_role_sets() const { return Storage().isMember("roleSets"); } /** * Clears the '<code>roleSets</code>' attribute. */ void clear_role_sets() { MutableStorage()->removeMember("roleSets"); } /** * Get a reference to the value of the '<code>roleSets</code>' attribute. */ const client::JsonCppArray<AboutAdditionalRoleInfoRoleSets > get_role_sets() const { const Json::Value& storage = Storage("roleSets"); return client::JsonValueToCppValueHelper<client::JsonCppArray<AboutAdditionalRoleInfoRoleSets > >(storage); } /** * Gets a reference to a mutable value of the '<code>roleSets</code>' * property. * * The supported additional roles per primary role. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<AboutAdditionalRoleInfoRoleSets > mutable_roleSets() { Json::Value* storage = MutableStorage("roleSets"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<AboutAdditionalRoleInfoRoleSets > >(storage); } /** * Determine if the '<code>type</code>' attribute was set. * * @return true if the '<code>type</code>' attribute was set. */ bool has_type() const { return Storage().isMember("type"); } /** * Clears the '<code>type</code>' attribute. */ void clear_type() { MutableStorage()->removeMember("type"); } /** * Get the value of the '<code>type</code>' attribute. */ const StringPiece get_type() const { const Json::Value& v = Storage("type"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>type</code>' attribute. * * The content type that this additional role info applies to. * * @param[in] value The new value. */ void set_type(const StringPiece& value) { *MutableStorage("type") = value.data(); } private: void operator=(const AboutAdditionalRoleInfo&); }; // AboutAdditionalRoleInfo /** * No description provided. * * @ingroup DataObject */ class AboutExportFormats : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static AboutExportFormats* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutExportFormats(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutExportFormats(Json::Value* storage); /** * Standard destructor. */ virtual ~AboutExportFormats(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::AboutExportFormats</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::AboutExportFormats"); } /** * Determine if the '<code>source</code>' attribute was set. * * @return true if the '<code>source</code>' attribute was set. */ bool has_source() const { return Storage().isMember("source"); } /** * Clears the '<code>source</code>' attribute. */ void clear_source() { MutableStorage()->removeMember("source"); } /** * Get the value of the '<code>source</code>' attribute. */ const StringPiece get_source() const { const Json::Value& v = Storage("source"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>source</code>' attribute. * * The content type to convert from. * * @param[in] value The new value. */ void set_source(const StringPiece& value) { *MutableStorage("source") = value.data(); } /** * Determine if the '<code>targets</code>' attribute was set. * * @return true if the '<code>targets</code>' attribute was set. */ bool has_targets() const { return Storage().isMember("targets"); } /** * Clears the '<code>targets</code>' attribute. */ void clear_targets() { MutableStorage()->removeMember("targets"); } /** * Get a reference to the value of the '<code>targets</code>' attribute. */ const client::JsonCppArray<string > get_targets() const { const Json::Value& storage = Storage("targets"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>targets</code>' * property. * * The possible content types to convert to. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_targets() { Json::Value* storage = MutableStorage("targets"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } private: void operator=(const AboutExportFormats&); }; // AboutExportFormats /** * No description provided. * * @ingroup DataObject */ class AboutFeatures : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static AboutFeatures* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutFeatures(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutFeatures(Json::Value* storage); /** * Standard destructor. */ virtual ~AboutFeatures(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::AboutFeatures</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::AboutFeatures"); } /** * Determine if the '<code>featureName</code>' attribute was set. * * @return true if the '<code>featureName</code>' attribute was set. */ bool has_feature_name() const { return Storage().isMember("featureName"); } /** * Clears the '<code>featureName</code>' attribute. */ void clear_feature_name() { MutableStorage()->removeMember("featureName"); } /** * Get the value of the '<code>featureName</code>' attribute. */ const StringPiece get_feature_name() const { const Json::Value& v = Storage("featureName"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>featureName</code>' attribute. * * The name of the feature. * * @param[in] value The new value. */ void set_feature_name(const StringPiece& value) { *MutableStorage("featureName") = value.data(); } /** * Determine if the '<code>featureRate</code>' attribute was set. * * @return true if the '<code>featureRate</code>' attribute was set. */ bool has_feature_rate() const { return Storage().isMember("featureRate"); } /** * Clears the '<code>featureRate</code>' attribute. */ void clear_feature_rate() { MutableStorage()->removeMember("featureRate"); } /** * Get the value of the '<code>featureRate</code>' attribute. */ double get_feature_rate() const { const Json::Value& storage = Storage("featureRate"); return client::JsonValueToCppValueHelper<double >(storage); } /** * Change the '<code>featureRate</code>' attribute. * * The request limit rate for this feature, in queries per second. * * @param[in] value The new value. */ void set_feature_rate(double value) { client::SetJsonValueFromCppValueHelper<double >( value, MutableStorage("featureRate")); } private: void operator=(const AboutFeatures&); }; // AboutFeatures /** * No description provided. * * @ingroup DataObject */ class AboutImportFormats : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static AboutImportFormats* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutImportFormats(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutImportFormats(Json::Value* storage); /** * Standard destructor. */ virtual ~AboutImportFormats(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::AboutImportFormats</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::AboutImportFormats"); } /** * Determine if the '<code>source</code>' attribute was set. * * @return true if the '<code>source</code>' attribute was set. */ bool has_source() const { return Storage().isMember("source"); } /** * Clears the '<code>source</code>' attribute. */ void clear_source() { MutableStorage()->removeMember("source"); } /** * Get the value of the '<code>source</code>' attribute. */ const StringPiece get_source() const { const Json::Value& v = Storage("source"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>source</code>' attribute. * * The imported file's content type to convert from. * * @param[in] value The new value. */ void set_source(const StringPiece& value) { *MutableStorage("source") = value.data(); } /** * Determine if the '<code>targets</code>' attribute was set. * * @return true if the '<code>targets</code>' attribute was set. */ bool has_targets() const { return Storage().isMember("targets"); } /** * Clears the '<code>targets</code>' attribute. */ void clear_targets() { MutableStorage()->removeMember("targets"); } /** * Get a reference to the value of the '<code>targets</code>' attribute. */ const client::JsonCppArray<string > get_targets() const { const Json::Value& storage = Storage("targets"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>targets</code>' * property. * * The possible content types to convert to. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_targets() { Json::Value* storage = MutableStorage("targets"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } private: void operator=(const AboutImportFormats&); }; // AboutImportFormats /** * No description provided. * * @ingroup DataObject */ class AboutMaxUploadSizes : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static AboutMaxUploadSizes* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutMaxUploadSizes(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutMaxUploadSizes(Json::Value* storage); /** * Standard destructor. */ virtual ~AboutMaxUploadSizes(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::AboutMaxUploadSizes</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::AboutMaxUploadSizes"); } /** * Determine if the '<code>size</code>' attribute was set. * * @return true if the '<code>size</code>' attribute was set. */ bool has_size() const { return Storage().isMember("size"); } /** * Clears the '<code>size</code>' attribute. */ void clear_size() { MutableStorage()->removeMember("size"); } /** * Get the value of the '<code>size</code>' attribute. */ int64 get_size() const { const Json::Value& storage = Storage("size"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>size</code>' attribute. * * The max upload size for this type. * * @param[in] value The new value. */ void set_size(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("size")); } /** * Determine if the '<code>type</code>' attribute was set. * * @return true if the '<code>type</code>' attribute was set. */ bool has_type() const { return Storage().isMember("type"); } /** * Clears the '<code>type</code>' attribute. */ void clear_type() { MutableStorage()->removeMember("type"); } /** * Get the value of the '<code>type</code>' attribute. */ const StringPiece get_type() const { const Json::Value& v = Storage("type"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>type</code>' attribute. * * The file type. * * @param[in] value The new value. */ void set_type(const StringPiece& value) { *MutableStorage("type") = value.data(); } private: void operator=(const AboutMaxUploadSizes&); }; // AboutMaxUploadSizes /** * No description provided. * * @ingroup DataObject */ class AboutQuotaBytesByService : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static AboutQuotaBytesByService* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutQuotaBytesByService(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutQuotaBytesByService(Json::Value* storage); /** * Standard destructor. */ virtual ~AboutQuotaBytesByService(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::AboutQuotaBytesByService</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::AboutQuotaBytesByService"); } /** * Determine if the '<code>bytesUsed</code>' attribute was set. * * @return true if the '<code>bytesUsed</code>' attribute was set. */ bool has_bytes_used() const { return Storage().isMember("bytesUsed"); } /** * Clears the '<code>bytesUsed</code>' attribute. */ void clear_bytes_used() { MutableStorage()->removeMember("bytesUsed"); } /** * Get the value of the '<code>bytesUsed</code>' attribute. */ int64 get_bytes_used() const { const Json::Value& storage = Storage("bytesUsed"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>bytesUsed</code>' attribute. * * The storage quota bytes used by the service. * * @param[in] value The new value. */ void set_bytes_used(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("bytesUsed")); } /** * Determine if the '<code>serviceName</code>' attribute was set. * * @return true if the '<code>serviceName</code>' attribute was set. */ bool has_service_name() const { return Storage().isMember("serviceName"); } /** * Clears the '<code>serviceName</code>' attribute. */ void clear_service_name() { MutableStorage()->removeMember("serviceName"); } /** * Get the value of the '<code>serviceName</code>' attribute. */ const StringPiece get_service_name() const { const Json::Value& v = Storage("serviceName"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>serviceName</code>' attribute. * * The service's name, e.g. DRIVE, GMAIL, or PHOTOS. * * @param[in] value The new value. */ void set_service_name(const StringPiece& value) { *MutableStorage("serviceName") = value.data(); } private: void operator=(const AboutQuotaBytesByService&); }; // AboutQuotaBytesByService /** * No description provided. * * @ingroup DataObject */ class AboutTeamDriveThemes : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static AboutTeamDriveThemes* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutTeamDriveThemes(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit AboutTeamDriveThemes(Json::Value* storage); /** * Standard destructor. */ virtual ~AboutTeamDriveThemes(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::AboutTeamDriveThemes</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::AboutTeamDriveThemes"); } /** * Determine if the '<code>backgroundImageLink</code>' attribute was set. * * @return true if the '<code>backgroundImageLink</code>' attribute was set. */ bool has_background_image_link() const { return Storage().isMember("backgroundImageLink"); } /** * Clears the '<code>backgroundImageLink</code>' attribute. */ void clear_background_image_link() { MutableStorage()->removeMember("backgroundImageLink"); } /** * Get the value of the '<code>backgroundImageLink</code>' attribute. */ const StringPiece get_background_image_link() const { const Json::Value& v = Storage("backgroundImageLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>backgroundImageLink</code>' attribute. * * A link to this Team Drive theme's background image. * * @param[in] value The new value. */ void set_background_image_link(const StringPiece& value) { *MutableStorage("backgroundImageLink") = value.data(); } /** * Determine if the '<code>colorRgb</code>' attribute was set. * * @return true if the '<code>colorRgb</code>' attribute was set. */ bool has_color_rgb() const { return Storage().isMember("colorRgb"); } /** * Clears the '<code>colorRgb</code>' attribute. */ void clear_color_rgb() { MutableStorage()->removeMember("colorRgb"); } /** * Get the value of the '<code>colorRgb</code>' attribute. */ const StringPiece get_color_rgb() const { const Json::Value& v = Storage("colorRgb"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>colorRgb</code>' attribute. * * The color of this Team Drive theme as an RGB hex string. * * @param[in] value The new value. */ void set_color_rgb(const StringPiece& value) { *MutableStorage("colorRgb") = value.data(); } /** * Determine if the '<code>id</code>' attribute was set. * * @return true if the '<code>id</code>' attribute was set. */ bool has_id() const { return Storage().isMember("id"); } /** * Clears the '<code>id</code>' attribute. */ void clear_id() { MutableStorage()->removeMember("id"); } /** * Get the value of the '<code>id</code>' attribute. */ const StringPiece get_id() const { const Json::Value& v = Storage("id"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>id</code>' attribute. * * The ID of the theme. * * @param[in] value The new value. */ void set_id(const StringPiece& value) { *MutableStorage("id") = value.data(); } private: void operator=(const AboutTeamDriveThemes&); }; // AboutTeamDriveThemes /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static About* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit About(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit About(Json::Value* storage); /** * Standard destructor. */ virtual ~About(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::About</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::About"); } /** * Determine if the '<code>additionalRoleInfo</code>' attribute was set. * * @return true if the '<code>additionalRoleInfo</code>' attribute was set. */ bool has_additional_role_info() const { return Storage().isMember("additionalRoleInfo"); } /** * Clears the '<code>additionalRoleInfo</code>' attribute. */ void clear_additional_role_info() { MutableStorage()->removeMember("additionalRoleInfo"); } /** * Get a reference to the value of the '<code>additionalRoleInfo</code>' * attribute. */ const client::JsonCppArray<AboutAdditionalRoleInfo > get_additional_role_info() const { const Json::Value& storage = Storage("additionalRoleInfo"); return client::JsonValueToCppValueHelper<client::JsonCppArray<AboutAdditionalRoleInfo > >(storage); } /** * Gets a reference to a mutable value of the * '<code>additionalRoleInfo</code>' property. * * Information about supported additional roles per file type. The most * specific type takes precedence. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<AboutAdditionalRoleInfo > mutable_additionalRoleInfo() { Json::Value* storage = MutableStorage("additionalRoleInfo"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<AboutAdditionalRoleInfo > >(storage); } /** * Determine if the '<code>domainSharingPolicy</code>' attribute was set. * * @return true if the '<code>domainSharingPolicy</code>' attribute was set. */ bool has_domain_sharing_policy() const { return Storage().isMember("domainSharingPolicy"); } /** * Clears the '<code>domainSharingPolicy</code>' attribute. */ void clear_domain_sharing_policy() { MutableStorage()->removeMember("domainSharingPolicy"); } /** * Get the value of the '<code>domainSharingPolicy</code>' attribute. */ const StringPiece get_domain_sharing_policy() const { const Json::Value& v = Storage("domainSharingPolicy"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>domainSharingPolicy</code>' attribute. * * The domain sharing policy for the current user. Possible values are: * - allowed * - allowedWithWarning * - incomingOnly * - disallowed. * * @param[in] value The new value. */ void set_domain_sharing_policy(const StringPiece& value) { *MutableStorage("domainSharingPolicy") = value.data(); } /** * Determine if the '<code>etag</code>' attribute was set. * * @return true if the '<code>etag</code>' attribute was set. */ bool has_etag() const { return Storage().isMember("etag"); } /** * Clears the '<code>etag</code>' attribute. */ void clear_etag() { MutableStorage()->removeMember("etag"); } /** * Get the value of the '<code>etag</code>' attribute. */ const StringPiece get_etag() const { const Json::Value& v = Storage("etag"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>etag</code>' attribute. * * The ETag of the item. * * @param[in] value The new value. */ void set_etag(const StringPiece& value) { *MutableStorage("etag") = value.data(); } /** * Determine if the '<code>exportFormats</code>' attribute was set. * * @return true if the '<code>exportFormats</code>' attribute was set. */ bool has_export_formats() const { return Storage().isMember("exportFormats"); } /** * Clears the '<code>exportFormats</code>' attribute. */ void clear_export_formats() { MutableStorage()->removeMember("exportFormats"); } /** * Get a reference to the value of the '<code>exportFormats</code>' attribute. */ const client::JsonCppArray<AboutExportFormats > get_export_formats() const { const Json::Value& storage = Storage("exportFormats"); return client::JsonValueToCppValueHelper<client::JsonCppArray<AboutExportFormats > >(storage); } /** * Gets a reference to a mutable value of the '<code>exportFormats</code>' * property. * * The allowable export formats. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<AboutExportFormats > mutable_exportFormats() { Json::Value* storage = MutableStorage("exportFormats"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<AboutExportFormats > >(storage); } /** * Determine if the '<code>features</code>' attribute was set. * * @return true if the '<code>features</code>' attribute was set. */ bool has_features() const { return Storage().isMember("features"); } /** * Clears the '<code>features</code>' attribute. */ void clear_features() { MutableStorage()->removeMember("features"); } /** * Get a reference to the value of the '<code>features</code>' attribute. */ const client::JsonCppArray<AboutFeatures > get_features() const { const Json::Value& storage = Storage("features"); return client::JsonValueToCppValueHelper<client::JsonCppArray<AboutFeatures > >(storage); } /** * Gets a reference to a mutable value of the '<code>features</code>' * property. * * List of additional features enabled on this account. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<AboutFeatures > mutable_features() { Json::Value* storage = MutableStorage("features"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<AboutFeatures > >(storage); } /** * Determine if the '<code>folderColorPalette</code>' attribute was set. * * @return true if the '<code>folderColorPalette</code>' attribute was set. */ bool has_folder_color_palette() const { return Storage().isMember("folderColorPalette"); } /** * Clears the '<code>folderColorPalette</code>' attribute. */ void clear_folder_color_palette() { MutableStorage()->removeMember("folderColorPalette"); } /** * Get a reference to the value of the '<code>folderColorPalette</code>' * attribute. */ const client::JsonCppArray<string > get_folder_color_palette() const { const Json::Value& storage = Storage("folderColorPalette"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the * '<code>folderColorPalette</code>' property. * * The palette of allowable folder colors as RGB hex strings. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_folderColorPalette() { Json::Value* storage = MutableStorage("folderColorPalette"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>importFormats</code>' attribute was set. * * @return true if the '<code>importFormats</code>' attribute was set. */ bool has_import_formats() const { return Storage().isMember("importFormats"); } /** * Clears the '<code>importFormats</code>' attribute. */ void clear_import_formats() { MutableStorage()->removeMember("importFormats"); } /** * Get a reference to the value of the '<code>importFormats</code>' attribute. */ const client::JsonCppArray<AboutImportFormats > get_import_formats() const { const Json::Value& storage = Storage("importFormats"); return client::JsonValueToCppValueHelper<client::JsonCppArray<AboutImportFormats > >(storage); } /** * Gets a reference to a mutable value of the '<code>importFormats</code>' * property. * * The allowable import formats. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<AboutImportFormats > mutable_importFormats() { Json::Value* storage = MutableStorage("importFormats"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<AboutImportFormats > >(storage); } /** * Determine if the '<code>isCurrentAppInstalled</code>' attribute was set. * * @return true if the '<code>isCurrentAppInstalled</code>' attribute was set. */ bool has_is_current_app_installed() const { return Storage().isMember("isCurrentAppInstalled"); } /** * Clears the '<code>isCurrentAppInstalled</code>' attribute. */ void clear_is_current_app_installed() { MutableStorage()->removeMember("isCurrentAppInstalled"); } /** * Get the value of the '<code>isCurrentAppInstalled</code>' attribute. */ bool get_is_current_app_installed() const { const Json::Value& storage = Storage("isCurrentAppInstalled"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>isCurrentAppInstalled</code>' attribute. * * A boolean indicating whether the authenticated app is installed by the * authenticated user. * * @param[in] value The new value. */ void set_is_current_app_installed(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("isCurrentAppInstalled")); } /** * Determine if the '<code>kind</code>' attribute was set. * * @return true if the '<code>kind</code>' attribute was set. */ bool has_kind() const { return Storage().isMember("kind"); } /** * Clears the '<code>kind</code>' attribute. */ void clear_kind() { MutableStorage()->removeMember("kind"); } /** * Get the value of the '<code>kind</code>' attribute. */ const StringPiece get_kind() const { const Json::Value& v = Storage("kind"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kind</code>' attribute. * * This is always drive#about. * * @param[in] value The new value. */ void set_kind(const StringPiece& value) { *MutableStorage("kind") = value.data(); } /** * Determine if the '<code>languageCode</code>' attribute was set. * * @return true if the '<code>languageCode</code>' attribute was set. */ bool has_language_code() const { return Storage().isMember("languageCode"); } /** * Clears the '<code>languageCode</code>' attribute. */ void clear_language_code() { MutableStorage()->removeMember("languageCode"); } /** * Get the value of the '<code>languageCode</code>' attribute. */ const StringPiece get_language_code() const { const Json::Value& v = Storage("languageCode"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>languageCode</code>' attribute. * * The user's language or locale code, as defined by BCP 47, with some * extensions from Unicode's LDML format * (http://www.unicode.org/reports/tr35/). * * @param[in] value The new value. */ void set_language_code(const StringPiece& value) { *MutableStorage("languageCode") = value.data(); } /** * Determine if the '<code>largestChangeId</code>' attribute was set. * * @return true if the '<code>largestChangeId</code>' attribute was set. */ bool has_largest_change_id() const { return Storage().isMember("largestChangeId"); } /** * Clears the '<code>largestChangeId</code>' attribute. */ void clear_largest_change_id() { MutableStorage()->removeMember("largestChangeId"); } /** * Get the value of the '<code>largestChangeId</code>' attribute. */ int64 get_largest_change_id() const { const Json::Value& storage = Storage("largestChangeId"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>largestChangeId</code>' attribute. * * The largest change id. * * @param[in] value The new value. */ void set_largest_change_id(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("largestChangeId")); } /** * Determine if the '<code>maxUploadSizes</code>' attribute was set. * * @return true if the '<code>maxUploadSizes</code>' attribute was set. */ bool has_max_upload_sizes() const { return Storage().isMember("maxUploadSizes"); } /** * Clears the '<code>maxUploadSizes</code>' attribute. */ void clear_max_upload_sizes() { MutableStorage()->removeMember("maxUploadSizes"); } /** * Get a reference to the value of the '<code>maxUploadSizes</code>' * attribute. */ const client::JsonCppArray<AboutMaxUploadSizes > get_max_upload_sizes() const { const Json::Value& storage = Storage("maxUploadSizes"); return client::JsonValueToCppValueHelper<client::JsonCppArray<AboutMaxUploadSizes > >(storage); } /** * Gets a reference to a mutable value of the '<code>maxUploadSizes</code>' * property. * * List of max upload sizes for each file type. The most specific type takes * precedence. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<AboutMaxUploadSizes > mutable_maxUploadSizes() { Json::Value* storage = MutableStorage("maxUploadSizes"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<AboutMaxUploadSizes > >(storage); } /** * Determine if the '<code>name</code>' attribute was set. * * @return true if the '<code>name</code>' attribute was set. */ bool has_name() const { return Storage().isMember("name"); } /** * Clears the '<code>name</code>' attribute. */ void clear_name() { MutableStorage()->removeMember("name"); } /** * Get the value of the '<code>name</code>' attribute. */ const StringPiece get_name() const { const Json::Value& v = Storage("name"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>name</code>' attribute. * * The name of the current user. * * @param[in] value The new value. */ void set_name(const StringPiece& value) { *MutableStorage("name") = value.data(); } /** * Determine if the '<code>permissionId</code>' attribute was set. * * @return true if the '<code>permissionId</code>' attribute was set. */ bool has_permission_id() const { return Storage().isMember("permissionId"); } /** * Clears the '<code>permissionId</code>' attribute. */ void clear_permission_id() { MutableStorage()->removeMember("permissionId"); } /** * Get the value of the '<code>permissionId</code>' attribute. */ const StringPiece get_permission_id() const { const Json::Value& v = Storage("permissionId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>permissionId</code>' attribute. * * The current user's ID as visible in the permissions collection. * * @param[in] value The new value. */ void set_permission_id(const StringPiece& value) { *MutableStorage("permissionId") = value.data(); } /** * Determine if the '<code>quotaBytesByService</code>' attribute was set. * * @return true if the '<code>quotaBytesByService</code>' attribute was set. */ bool has_quota_bytes_by_service() const { return Storage().isMember("quotaBytesByService"); } /** * Clears the '<code>quotaBytesByService</code>' attribute. */ void clear_quota_bytes_by_service() { MutableStorage()->removeMember("quotaBytesByService"); } /** * Get a reference to the value of the '<code>quotaBytesByService</code>' * attribute. */ const client::JsonCppArray<AboutQuotaBytesByService > get_quota_bytes_by_service() const { const Json::Value& storage = Storage("quotaBytesByService"); return client::JsonValueToCppValueHelper<client::JsonCppArray<AboutQuotaBytesByService > >(storage); } /** * Gets a reference to a mutable value of the * '<code>quotaBytesByService</code>' property. * * The amount of storage quota used by different Google services. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<AboutQuotaBytesByService > mutable_quotaBytesByService() { Json::Value* storage = MutableStorage("quotaBytesByService"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<AboutQuotaBytesByService > >(storage); } /** * Determine if the '<code>quotaBytesTotal</code>' attribute was set. * * @return true if the '<code>quotaBytesTotal</code>' attribute was set. */ bool has_quota_bytes_total() const { return Storage().isMember("quotaBytesTotal"); } /** * Clears the '<code>quotaBytesTotal</code>' attribute. */ void clear_quota_bytes_total() { MutableStorage()->removeMember("quotaBytesTotal"); } /** * Get the value of the '<code>quotaBytesTotal</code>' attribute. */ int64 get_quota_bytes_total() const { const Json::Value& storage = Storage("quotaBytesTotal"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>quotaBytesTotal</code>' attribute. * * The total number of quota bytes. * * @param[in] value The new value. */ void set_quota_bytes_total(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("quotaBytesTotal")); } /** * Determine if the '<code>quotaBytesUsed</code>' attribute was set. * * @return true if the '<code>quotaBytesUsed</code>' attribute was set. */ bool has_quota_bytes_used() const { return Storage().isMember("quotaBytesUsed"); } /** * Clears the '<code>quotaBytesUsed</code>' attribute. */ void clear_quota_bytes_used() { MutableStorage()->removeMember("quotaBytesUsed"); } /** * Get the value of the '<code>quotaBytesUsed</code>' attribute. */ int64 get_quota_bytes_used() const { const Json::Value& storage = Storage("quotaBytesUsed"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>quotaBytesUsed</code>' attribute. * * The number of quota bytes used by Google Drive. * * @param[in] value The new value. */ void set_quota_bytes_used(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("quotaBytesUsed")); } /** * Determine if the '<code>quotaBytesUsedAggregate</code>' attribute was set. * * @return true if the '<code>quotaBytesUsedAggregate</code>' attribute was * set. */ bool has_quota_bytes_used_aggregate() const { return Storage().isMember("quotaBytesUsedAggregate"); } /** * Clears the '<code>quotaBytesUsedAggregate</code>' attribute. */ void clear_quota_bytes_used_aggregate() { MutableStorage()->removeMember("quotaBytesUsedAggregate"); } /** * Get the value of the '<code>quotaBytesUsedAggregate</code>' attribute. */ int64 get_quota_bytes_used_aggregate() const { const Json::Value& storage = Storage("quotaBytesUsedAggregate"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>quotaBytesUsedAggregate</code>' attribute. * * The number of quota bytes used by all Google apps (Drive, Picasa, etc.). * * @param[in] value The new value. */ void set_quota_bytes_used_aggregate(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("quotaBytesUsedAggregate")); } /** * Determine if the '<code>quotaBytesUsedInTrash</code>' attribute was set. * * @return true if the '<code>quotaBytesUsedInTrash</code>' attribute was set. */ bool has_quota_bytes_used_in_trash() const { return Storage().isMember("quotaBytesUsedInTrash"); } /** * Clears the '<code>quotaBytesUsedInTrash</code>' attribute. */ void clear_quota_bytes_used_in_trash() { MutableStorage()->removeMember("quotaBytesUsedInTrash"); } /** * Get the value of the '<code>quotaBytesUsedInTrash</code>' attribute. */ int64 get_quota_bytes_used_in_trash() const { const Json::Value& storage = Storage("quotaBytesUsedInTrash"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>quotaBytesUsedInTrash</code>' attribute. * * The number of quota bytes used by trashed items. * * @param[in] value The new value. */ void set_quota_bytes_used_in_trash(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("quotaBytesUsedInTrash")); } /** * Determine if the '<code>quotaType</code>' attribute was set. * * @return true if the '<code>quotaType</code>' attribute was set. */ bool has_quota_type() const { return Storage().isMember("quotaType"); } /** * Clears the '<code>quotaType</code>' attribute. */ void clear_quota_type() { MutableStorage()->removeMember("quotaType"); } /** * Get the value of the '<code>quotaType</code>' attribute. */ const StringPiece get_quota_type() const { const Json::Value& v = Storage("quotaType"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>quotaType</code>' attribute. * * The type of the user's storage quota. Possible values are: * - LIMITED * - UNLIMITED. * * @param[in] value The new value. */ void set_quota_type(const StringPiece& value) { *MutableStorage("quotaType") = value.data(); } /** * Determine if the '<code>remainingChangeIds</code>' attribute was set. * * @return true if the '<code>remainingChangeIds</code>' attribute was set. */ bool has_remaining_change_ids() const { return Storage().isMember("remainingChangeIds"); } /** * Clears the '<code>remainingChangeIds</code>' attribute. */ void clear_remaining_change_ids() { MutableStorage()->removeMember("remainingChangeIds"); } /** * Get the value of the '<code>remainingChangeIds</code>' attribute. */ int64 get_remaining_change_ids() const { const Json::Value& storage = Storage("remainingChangeIds"); return client::JsonValueToCppValueHelper<int64 >(storage); } /** * Change the '<code>remainingChangeIds</code>' attribute. * * The number of remaining change ids, limited to no more than 2500. * * @param[in] value The new value. */ void set_remaining_change_ids(int64 value) { client::SetJsonValueFromCppValueHelper<int64 >( value, MutableStorage("remainingChangeIds")); } /** * Determine if the '<code>rootFolderId</code>' attribute was set. * * @return true if the '<code>rootFolderId</code>' attribute was set. */ bool has_root_folder_id() const { return Storage().isMember("rootFolderId"); } /** * Clears the '<code>rootFolderId</code>' attribute. */ void clear_root_folder_id() { MutableStorage()->removeMember("rootFolderId"); } /** * Get the value of the '<code>rootFolderId</code>' attribute. */ const StringPiece get_root_folder_id() const { const Json::Value& v = Storage("rootFolderId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>rootFolderId</code>' attribute. * * The id of the root folder. * * @param[in] value The new value. */ void set_root_folder_id(const StringPiece& value) { *MutableStorage("rootFolderId") = value.data(); } /** * Determine if the '<code>selfLink</code>' attribute was set. * * @return true if the '<code>selfLink</code>' attribute was set. */ bool has_self_link() const { return Storage().isMember("selfLink"); } /** * Clears the '<code>selfLink</code>' attribute. */ void clear_self_link() { MutableStorage()->removeMember("selfLink"); } /** * Get the value of the '<code>selfLink</code>' attribute. */ const StringPiece get_self_link() const { const Json::Value& v = Storage("selfLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>selfLink</code>' attribute. * * A link back to this item. * * @param[in] value The new value. */ void set_self_link(const StringPiece& value) { *MutableStorage("selfLink") = value.data(); } /** * Determine if the '<code>teamDriveThemes</code>' attribute was set. * * @return true if the '<code>teamDriveThemes</code>' attribute was set. */ bool has_team_drive_themes() const { return Storage().isMember("teamDriveThemes"); } /** * Clears the '<code>teamDriveThemes</code>' attribute. */ void clear_team_drive_themes() { MutableStorage()->removeMember("teamDriveThemes"); } /** * Get a reference to the value of the '<code>teamDriveThemes</code>' * attribute. */ const client::JsonCppArray<AboutTeamDriveThemes > get_team_drive_themes() const { const Json::Value& storage = Storage("teamDriveThemes"); return client::JsonValueToCppValueHelper<client::JsonCppArray<AboutTeamDriveThemes > >(storage); } /** * Gets a reference to a mutable value of the '<code>teamDriveThemes</code>' * property. * * A list of themes that are supported for Team Drives. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<AboutTeamDriveThemes > mutable_teamDriveThemes() { Json::Value* storage = MutableStorage("teamDriveThemes"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<AboutTeamDriveThemes > >(storage); } /** * Determine if the '<code>user</code>' attribute was set. * * @return true if the '<code>user</code>' attribute was set. */ bool has_user() const { return Storage().isMember("user"); } /** * Clears the '<code>user</code>' attribute. */ void clear_user() { MutableStorage()->removeMember("user"); } /** * Get a reference to the value of the '<code>user</code>' attribute. */ const User get_user() const; /** * Gets a reference to a mutable value of the '<code>user</code>' property. * * The authenticated user. * * @return The result can be modified to change the attribute value. */ User mutable_user(); private: void operator=(const About&); }; // About } // namespace google_drive_api #endif // GOOGLE_DRIVE_API_ABOUT_H_ <file_sep>/src/samples/CMakeLists.txt project (GoogleApis_C++_Samples) include_directories(${GFLAGS_INCLUDES}) INCLUDE_DIRECTORIES(${GOOGLEAPIS_SERVICE_REPOSITORY_DIR}/calendar) INCLUDE_DIRECTORIES(${GOOGLEAPIS_SERVICE_REPOSITORY_DIR}/drive) INCLUDE_DIRECTORIES(${GOOGLEAPIS_SERVICE_REPOSITORY_DIR}/youtube) # This is the basic sample from the tutorial add_executable(calendar_sample calendar_sample_main.cc) target_link_libraries(calendar_sample google_calendar_api) target_link_libraries(calendar_sample googleapis_jsoncpp) target_link_libraries(calendar_sample googleapis_curl_http) target_link_libraries(calendar_sample googleapis_http) target_link_libraries(calendar_sample googleapis_oauth2) target_link_libraries(calendar_sample googleapis_utils) if (HAVE_OPENSSL) target_link_libraries(calendar_sample googleapis_openssl_codec) endif() target_link_libraries(calendar_sample ${GFLAGS_LIBRARY}) target_link_libraries(calendar_sample pthread) # A helper library used by other samples # It provides a shell command processor for sending messages interactively. add_library(sample_contrib STATIC command_processor.cc installed_application.cc) target_link_libraries(sample_contrib googleapis_http) target_link_libraries(sample_contrib googleapis_oauth2) target_link_libraries(sample_contrib googleapis_mongoose) target_link_libraries(sample_contrib googleapis_utils) if (HAVE_OPENSSL) target_link_libraries(sample_contrib googleapis_openssl_codec) endif() # A sample that interacts with the GDrive Service. add_executable(gdrive_sample gdriveutil_main.cc) target_link_libraries(gdrive_sample google_drive_api) target_link_libraries(gdrive_sample sample_contrib) target_link_libraries(gdrive_sample googleapis_jsoncpp) target_link_libraries(gdrive_sample googleapis_curl_http) target_link_libraries(gdrive_sample googleapis_http) target_link_libraries(gdrive_sample googleapis_oauth2) target_link_libraries(gdrive_sample googleapis_utils) target_link_libraries(gdrive_sample ${GFLAGS_LIBRARY}) # A sample that interacts with the YouTube Service for Live Broadcasts. add_executable(youtube_broadcast_sample youtube_broadcast_main.cc) target_link_libraries(youtube_broadcast_sample youtube_api) target_link_libraries(youtube_broadcast_sample sample_contrib) target_link_libraries(youtube_broadcast_sample googleapis_jsoncpp) target_link_libraries(youtube_broadcast_sample googleapis_curl_http) target_link_libraries(youtube_broadcast_sample googleapis_http) target_link_libraries(youtube_broadcast_sample googleapis_oauth2) target_link_libraries(youtube_broadcast_sample googleapis_utils) target_link_libraries(youtube_broadcast_sample ${GFLAGS_LIBRARY}) add_executable(webflow_sample webflow_sample_main.cc abstract_gplus_login_flow.cc abstract_login_flow.cc abstract_webserver_login_flow.cc) target_link_libraries(webflow_sample sample_contrib) target_link_libraries(webflow_sample googleapis_jsoncpp) target_link_libraries(webflow_sample googleapis_curl_http) target_link_libraries(webflow_sample googleapis_http) target_link_libraries(webflow_sample googleapis_oauth2) target_link_libraries(webflow_sample googleapis_utils) target_link_libraries(webflow_sample ${GFLAGS_LIBRARY}) <file_sep>/service_apis/youtube/google/youtube_api/live_chat_fan_funding_event_details.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_LIVE_CHAT_FAN_FUNDING_EVENT_DETAILS_H_ #define GOOGLE_YOUTUBE_API_LIVE_CHAT_FAN_FUNDING_EVENT_DETAILS_H_ #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * No description provided. * * @ingroup DataObject */ class LiveChatFanFundingEventDetails : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static LiveChatFanFundingEventDetails* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveChatFanFundingEventDetails(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveChatFanFundingEventDetails(Json::Value* storage); /** * Standard destructor. */ virtual ~LiveChatFanFundingEventDetails(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::LiveChatFanFundingEventDetails</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::LiveChatFanFundingEventDetails"); } /** * Determine if the '<code>amountDisplayString</code>' attribute was set. * * @return true if the '<code>amountDisplayString</code>' attribute was set. */ bool has_amount_display_string() const { return Storage().isMember("amountDisplayString"); } /** * Clears the '<code>amountDisplayString</code>' attribute. */ void clear_amount_display_string() { MutableStorage()->removeMember("amountDisplayString"); } /** * Get the value of the '<code>amountDisplayString</code>' attribute. */ const StringPiece get_amount_display_string() const { const Json::Value& v = Storage("amountDisplayString"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>amountDisplayString</code>' attribute. * * A rendered string that displays the fund amount and currency to the user. * * @param[in] value The new value. */ void set_amount_display_string(const StringPiece& value) { *MutableStorage("amountDisplayString") = value.data(); } /** * Determine if the '<code>amountMicros</code>' attribute was set. * * @return true if the '<code>amountMicros</code>' attribute was set. */ bool has_amount_micros() const { return Storage().isMember("amountMicros"); } /** * Clears the '<code>amountMicros</code>' attribute. */ void clear_amount_micros() { MutableStorage()->removeMember("amountMicros"); } /** * Get the value of the '<code>amountMicros</code>' attribute. */ uint64 get_amount_micros() const { const Json::Value& storage = Storage("amountMicros"); return client::JsonValueToCppValueHelper<uint64 >(storage); } /** * Change the '<code>amountMicros</code>' attribute. * * The amount of the fund. * * @param[in] value The new value. */ void set_amount_micros(uint64 value) { client::SetJsonValueFromCppValueHelper<uint64 >( value, MutableStorage("amountMicros")); } /** * Determine if the '<code>currency</code>' attribute was set. * * @return true if the '<code>currency</code>' attribute was set. */ bool has_currency() const { return Storage().isMember("currency"); } /** * Clears the '<code>currency</code>' attribute. */ void clear_currency() { MutableStorage()->removeMember("currency"); } /** * Get the value of the '<code>currency</code>' attribute. */ const StringPiece get_currency() const { const Json::Value& v = Storage("currency"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>currency</code>' attribute. * * The currency in which the fund was made. * * @param[in] value The new value. */ void set_currency(const StringPiece& value) { *MutableStorage("currency") = value.data(); } /** * Determine if the '<code>userComment</code>' attribute was set. * * @return true if the '<code>userComment</code>' attribute was set. */ bool has_user_comment() const { return Storage().isMember("userComment"); } /** * Clears the '<code>userComment</code>' attribute. */ void clear_user_comment() { MutableStorage()->removeMember("userComment"); } /** * Get the value of the '<code>userComment</code>' attribute. */ const StringPiece get_user_comment() const { const Json::Value& v = Storage("userComment"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>userComment</code>' attribute. * * The comment added by the user to this fan funding event. * * @param[in] value The new value. */ void set_user_comment(const StringPiece& value) { *MutableStorage("userComment") = value.data(); } private: void operator=(const LiveChatFanFundingEventDetails&); }; // LiveChatFanFundingEventDetails } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_LIVE_CHAT_FAN_FUNDING_EVENT_DETAILS_H_ <file_sep>/prepare_dependencies.py #!/usr/bin/python # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Prepares dependencies for Google APIs Client Library for C++. This *might* download, configure, build, and install the libraries we depend on in whole or part. It is almost always not exactly you really want, because each of the dependencies releases on their own cycle, faster than this script will track them. For the most repeatable build process, developers should manually pull the individual packages from their respective repositories, inspect their licenses, add them to their local revision control, and integrate into their build system. Since this script is only marginally maintained, if it does not work for you, your best options is to install the required components by hand. Usage: By default, with no args, this will run turnkey doing whatever is needed. The provided options let you fine tune running specific packages. For example, if you need to upgrade a dependency or build again. To force a dependency to rebuild, use --force. [-b] Just build the dependent packages in the --download_dir [-d] Just download the dependent packages to the --download_dir [-i] Just install the dependencies to the --install_dir [--force] Ignore any previous results and force the request from scratch. [--download_dir=<path>] Specifies the download_dir. The default path is ./external_dependencies. [--install_dir=<path>] Specifies the install_dir. The default path is ./external_dependencies/install. [cmake|curl|gflags|glog|gmock]* Process just the specific subset. If you wish to obtain and build a newer (or older) version of a dependency, simply change the url in this file and run this script again on that name with the --force flag. """ import getopt import glob import os import platform import shutil import subprocess import sys import tarfile import urllib import zipfile COMPILED_MARKER = '_built' INSTALLED_MARKER = '_installed' CONFIGURED_MARKER = '_configured' CYGWIN_PLATFORM = 'cygwin' WINDOWS_PLATFORM = 'windows' OSX_PLATFORM = 'osx' LINUX_PLATFORM = 'Linux' VS_COMPILER = 'VisualStudio' GCC_COMPILER = 'gcc' AUTO_CONFIG = 'auto' CONFIGURE_CONFIG = 'configure' CMAKE_CONFIG = 'cmake' class ConfigInfo(object): """Configuration information for how to build the dependencies.""" def __init__(self, abs_root_dir, unused_argv): """Initialize Configuration Information. Args: abs_root_dir: (sring) The path tot he build root directory. unused_argv: (string) The program arguments, including argv[0]. """ self._abs_root_dir = '%s' % abs_root_dir self._download_packages = False self._build_packages = False self._install_packages = False self._force = False self._download_dir = os.path.join(abs_root_dir, 'external_dependencies') self._abs_install_dir = '%s' % os.path.join( os.getcwd(), os.path.join('external_dependencies', 'install')) self._compiler = GCC_COMPILER if os.name == 'nt': self._port_name = WINDOWS_PLATFORM self._compiler = VS_COMPILER elif platform.system().startswith('CYGWIN'): self._port_name = CYGWIN_PLATFORM elif platform.system() == 'Darwin': self._port_name = OSX_PLATFORM elif platform.system() == 'Linux': self._port_name = LINUX_PLATFORM else: print 'Unknown system = %s. Assuming it is Linux compatible.' % ( platform.system()) self._port_name = LINUX_PLATFORM return def SetOptions(self, options): """Sets custom options. Args: options: (list[string, string]) name, value pairs of options given """ do_all = True for opt, arg in options: if opt == '-b': do_all = False self._build_packages = True elif opt == '-d': do_all = False self._download_packages = True elif opt == '-i': do_all = False self._install_packages = True elif opt == '--force': self._force = True elif opt == '--download_dir': self._download_dir = arg elif opt == '--install_dir': if arg.startswith('/'): self._abs_install_dir = '%s' % arg else: self._abs_install_dir = os.path.join('%s' % os.getcwd(), arg) if do_all: self._build_packages = True self._download_packages = True self._install_packages = True if self._build_packages: print ' Build packages = True' if self._download_packages: print ' Download packages = True' if self._install_packages: print ' Installing packages = True' if self._download_packages: print ' Downloading files to %s' % self._download_dir if not os.path.exists(self._download_dir): os.makedirs(self._download_dir) if self._install_packages: print ' Installing packages to %s' % self._abs_install_dir if not os.path.exists(os.path.join(self._abs_install_dir, 'lib')): os.makedirs(os.path.join(self._abs_install_dir, 'lib')) if not os.path.exists(os.path.join(self._abs_install_dir, 'include')): os.makedirs(os.path.join(self._abs_install_dir, 'include')) @property def build_packages(self): """Returns whether we wwant to compile the packages.""" return self._build_packages @property def download_packages(self): """Returns whether we wwant to download the packages.""" return self._download_packages @property def install_packages(self): """Returns whether we wwant to install the packages.""" return self._install_packages @property def compiler(self): """Returns the name of the compiler we prefer.""" return self._compiler @property def port(self): """Returns the name of the platform we are preparing.""" return self._port_name @property def make_command(self): """A tuple of (make_program_path, make_argument_list) for using Make.""" if os.name == 'nt': program = 'nmake' args = '/C' else: program = 'make' args = '' return (program, args) @property def cmake_command(self): """A tuple of (cmake_program_path, cmake_argument_list) for using CMake.""" if self._port_name == WINDOWS_PLATFORM: program = 'cmake' args = '-G "NMake Makefiles"' elif self._port_name == CYGWIN_PLATFORM: program = 'cmake' args = '-G "Unix Makefiles"' else: program = os.path.join(self._abs_install_dir, 'bin', 'cmake') args = '' return (program, args) @property def force(self): """Force all the work to be done again.""" return self._force @property def download_dir(self): """The directory that we'll download and build external packages in.""" return self._download_dir @property def abs_install_dir(self): """The root directory for the external dependency installation dir.""" return self._abs_install_dir @property def abs_root_dir(self): """The root directory for the Google APIs for C++ sources.""" return self._abs_root_dir def _DownloadStatusHook(a, b, c): """Shows progress of download.""" print '% 3.1f%% of %d bytes\r' % (min(100, float(a * b) / c * 100), c) class PackageInstaller(object): """Acquires, builds, and installs an individual package for use in the SDK. """ def __init__(self, config, url, make_target='all', package_name='', config_type=AUTO_CONFIG, extra_configure_flags=''): """Initializes for the individual package located at the given URL. Args: config: (Installer) The installer contains configuration info. url: (string) The url to install. make_target: (string) The make target to use when compiling. package_name: (string) Explicit package name if different than indicated by the URL's archive. config_type: (string) Specifies how this package is configured. extra_configure_flags: (string) Nonstandard flags for ./configure """ self._config = config self._url = url self._config_type = config_type self._extra_configure_flags = extra_configure_flags self._extra_cppflags = '' self._extra_ldflags = '' self._make_target = make_target self._archive_file = os.path.split(url)[1] if not package_name: package_name = PackageInstaller._ArchiveToPackage(self._archive_file) self._package_name = package_name self._package_path = os.path.join(config.download_dir, self._package_name) self._vc_project_path = '' self._vc_upgrade_from_project_path = '' self._msbuild_args = '' def UpgradeVisualStudio(self, from_project, to_project): """Upgrades visual studio project. Args: from_project: (string) The path of the project to convert from. to_project: (string) The path of the project to convert to. (conversion might be in-place). """ if from_project == to_project or not os.path.exists(to_project): print '>>> Upgrading %s' % from_project upgrade_cmd = 'devenv "%s" /upgrade' % from_project PackageInstaller.RunOrDie( upgrade_cmd, 'Devenv failed to upgrade project.') def Download(self): """Downloads URL to file in configured download_dir.""" config = self._config url = self._url filename = self._archive_file download_dir = config.download_dir download_path = os.path.join(download_dir, filename) if os.path.exists(download_path) and not config.force: print '%s already exists - skipping download from %s' % (filename, url) return print 'Downloading %s from %s: ' % (filename, url) try: urllib.urlretrieve(url, download_path, _DownloadStatusHook) except IOError: print ('\nERROR:\n' 'Could not download %s.\n' % url + ('It could be that this particular version is no longer' ' available.\n' 'Check the site where the url is coming from.\n' 'If there is a more recent version then:\n' ' 1) Edit this script to change the old url to the new one.\n' ' 2) Run the script again.\n' ' It will pick up where it left off, using the new url.' '\n')) sys.exit(1) def MaybeTweakAfterUnpackage(self): """Extra stuff to do after unpackaging an archive.""" config = self._config if config.compiler == VS_COMPILER and self._vc_upgrade_from_project_path: proj_dir = os.path.split(self._vc_project_path)[0] marker = os.path.join(proj_dir, '_upgraded_vc') if os.path.exists(self._vc_project_path) and config.force: if self._vc_upgrade_from_project_path != self._vc_project_path: os.unlink(self._vc_project_path) if os.path.exists(marker): os.unlink(marker) if (not os.path.exists(self._vc_project_path) or self._vc_project_path == self._vc_upgrade_from_project_path): self.UpgradeVisualStudio(self._vc_upgrade_from_project_path, self._vc_project_path) open(marker, 'w').close() def Unpackage(self): """Unpackages the archive into the package if needed.""" config = self._config download_dir = config.download_dir archive_filename = self._archive_file package = self._package_name os.chdir(download_dir) if not os.path.exists(archive_filename): print '%s does not exist in %s' % ( archive_filename, config.download_dir) sys.exit(1) if os.path.exists(self._package_name): if not config.force: self.MaybeTweakAfterUnpackage() return print 'Removing existing %s' % self._package_name shutil.rmtree(self._package_name) print '\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>' print '>>> Unpacking %s into %s' % (archive_filename, package) if archive_filename.endswith('zip'): z = zipfile.ZipFile(archive_filename) for elem in z.namelist(): dirname, filename = os.path.split(elem) if not os.path.exists(dirname): os.makedirs(dirname) if filename: with open(elem, 'w') as f: f.write(z.read(elem)) z.close() elif archive_filename.endswith('.bz2'): try: subprocess.call('tar -xjf %s' % archive_filename, shell=True) except OSError: print 'Failed to unpack %s' % archive_filename sys.exit(-1) else: try: tar = tarfile.open(archive_filename) tar.extractall() tar.close() except IOError: try: subprocess.call('tar -xf %s' % archive_filename, shell=True) except OSError: print 'Failed to unpack %s' % archive_filename sys.exit(-1) self.MaybeTweakAfterUnpackage() print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>' def DetermineConfigType(self, path): """Detemines how to configure the directory depending on files. Args: path: (string) The path to be configured. Returns: The method to use for configuring the package. """ if self._vc_project_path and self._config.compiler == VS_COMPILER: return None if os.path.exists(os.path.join(path, 'CMakeLists.txt')): return CMAKE_CONFIG if os.path.exists(os.path.join(path, 'configure')): return CONFIGURE_CONFIG if os.path.exists(os.path.join(path, 'Configure')): return CONFIGURE_CONFIG print 'Could not determine how to configure %s' % path sys.exit(1) def Configure(self): """Configure the package.""" config = self._config os.chdir(self._package_path) marker_path = CONFIGURED_MARKER if os.path.exists(marker_path): if not config.force: print '%s already configured' % self._package_name return # remove built since we are forcing a rebuild os.unlink(marker_path) config_type = self._config_type if config_type == AUTO_CONFIG: config_type = self.DetermineConfigType('.') if not config_type: pass elif config_type == CMAKE_CONFIG: configure_cmd = '%s %s' % ( config.cmake_command[0], config.cmake_command[1]) prefix_arg = '-DCMAKE_INSTALL_PREFIX:PATH="%s" .' % ( config.abs_install_dir) elif config_type == CONFIGURE_CONFIG: # Normally the automake uses a script called 'configure' # but for some reason openssl calls it 'Configure'. configure_cmd = os.path.join('.', 'configure') if not os.path.exists(configure_cmd): configure_cmd = os.path.join('.', 'Configure') prefix_arg = '--prefix="%s" %s' % ( config.abs_install_dir, self._extra_configure_flags) if not config_type: cmd = None elif config.port == WINDOWS_PLATFORM: cmd = '%s %s' % (configure_cmd, prefix_arg) else: ldflags = '-L%s/lib %s' % ( config.abs_install_dir, self._extra_ldflags) cppflags = '-I%s/include %s' % ( config.abs_install_dir, self._extra_cppflags) cmd = 'LDFLAGS="%s" CPPFLAGS="%s" %s %s' % ( ldflags, cppflags, configure_cmd, prefix_arg) if cmd: PackageInstaller.RunOrDie( cmd, 'Failed to configure %s' % self._package_name) # touch file so we know we configured it. open(marker_path, 'w').close() print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>' print '>>> Finished configuring %s' % self._package_name print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n' def Compile(self): """Compiles a package but does not install it.""" package_name = self._package_name config = self._config os.chdir(self._package_path) marker_path = COMPILED_MARKER if os.path.exists(marker_path): if not config.force: print '%s already built' % package_name return # remove built since we are forcing a rebuild os.unlink(marker_path) PackageInstaller._VerifyMakeOrDie(config.make_command[0]) print '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++' print '+++ Building %s [%s]' % (package_name, self._make_target) print '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++' if self._vc_project_path and config.compiler == VS_COMPILER: dirname, filename = os.path.split(self._vc_project_path) os.chdir(dirname) make_cmd = 'msbuild "%s" %s' % (filename, self._msbuild_args) else: make_cmd = '%s %s %s' % ( config.make_command[0], config.make_command[1], self._make_target) PackageInstaller.RunOrDie(make_cmd, 'Failed to make %s' % package_name) # touch file so we know we built it. open(marker_path, 'w').close() print '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++' print '+++ Finished building %s' % package_name print '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n' def Install(self): """Installs a pre-built package using a make-rule.""" self.MakeInstall() def MakeInstall(self): """Installs a pre-built package, including ones we built ourself.""" package_name = self._package_name config = self._config os.chdir(self._package_path) marker_path = INSTALLED_MARKER if os.path.exists(marker_path): if not config.force: print '%s already installed' % package_name return # remove built since we are forcing an install os.unlink(marker_path) PackageInstaller._VerifyMakeOrDie(config.make_command[0]) print '\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++' print '+++ Installing %s' % package_name print '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++' cmd = '%s %s install' % config.make_command PackageInstaller.RunOrDie(cmd, 'Failed to install %s' % package_name) # touch file so we know we installed it. open(marker_path, 'w').close() print '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++' print '+++ Finished installing %s' % package_name print '++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++' def Process(self): """Runs standard workflow to obatin and prepare dependencies.""" config = self._config if config.download_packages: self.Download() if config.build_packages or config.install_packages: self.Unpackage() if config.build_packages or config.install_packages: self.Configure() if config.build_packages: self.Compile() if config.install_packages: self.Install() @classmethod def CopyAllFiles(cls, from_dir, to_dir): """Copies one directory tree into another. Args: from_dir: (string) The directory to copy from. to_dir: (string) The directory to copy to. """ for elem in glob.glob(os.path.join(from_dir, '*')): tail = os.path.split(elem)[1] if os.path.isdir(elem): targetdir = os.path.join(to_dir, tail) if not os.path.exists(targetdir): os.makedirs(targetdir) PackageInstaller.CopyAllFiles(elem, targetdir) else: targetfile = os.path.join(to_dir, tail) shutil.copyfile(elem, targetfile) shutil.copystat(elem, targetfile) @classmethod def RunOrDie(cls, cmd, error_msg): """Runs system command. Dies if the command fails. Args: cmd: (string) Command to execute. error_msg: (string) Optional additional error to print on failure. """ try: print '>>> Executing [%s] in %s' % (cmd, os.getcwd()) ok = os.system(cmd) == 0 except OSError: ok = False if not ok: print 'Failed command: [%s] in %s' % (cmd, os.getcwd()) if error_msg: print ' %s' % error_msg sys.exit(1) @classmethod def _ArchiveToPackage(cls, archive): """Return the package name for a given archive. Usually this is the archive name stripped of the .tar.gz or .zip suffix. Args: archive: (string) A tar or zip file. Returns: The package name of the archive strips the .tar.gz or .zip extension. """ for suffix in ['.tar.gz', '.zip', '.tgz', '.tar.bz2']: if archive.endswith(suffix): return archive[0:len(archive) - len(suffix)] print 'Unhandled archive=%s' % archive sys.exit(1) @classmethod def _VerifyCMakeOrDie(cls, cmake_program): """Verifies that CMake is on the path or exits. Args: cmake_program: (string) The cmake program to check for. """ if not cls._VerifyProgram(cmake_program, '--version'): print('Could not find "cmake" on your PATH. ' 'Try running this script again with the arguments ' '"-di cmake".\n' 'Then try building and installing again.') exit(1) @classmethod def _VerifyMakeOrDie(cls, make_program): """Verifies that the make_program variable is on the path or exits. Args: make_program: (string) The make program to check for. """ install_instructions = '' args = '--version' if os.name == 'nt': args = '/C /HELP' install_instructions = ( 'If you are using Visual Studio, try running the vcvars.bat script ' ' for the version of Visual Studio you wish to use. ' ' For 64-bit Visual Studio 11.0 this is something like ' ' C:\\"Program Files (x86)"\\"Microsoft Visual Studio 11.0"' '\\VC\\bin\\x86_amd64\\vcvars64.bat') if not cls._VerifyProgram(make_program, args): print('Make sure that "%s" is in your path. %s' % ( make_program, install_instructions)) exit(1) @classmethod def _VerifyProgram(cls, prog, args): """Verify the program exists on the path. Args: prog: (string) The name of the program to check. args: (string) args to give program when running it. Returns: True if program is on PATH, False otherwise. """ try: test = '%s %s' % (prog, args) subprocess.Popen(test, stdout=subprocess.PIPE, shell=True) except OSError: return False return True class MongoosePackageInstaller(PackageInstaller): """Custom installer for the Mongoose package.""" def __init__(self, config, url, package_path='mongoose'): """Standard PackageInstaller initializer.""" super(MongoosePackageInstaller, self).__init__(config, url) self._config_type = CMAKE_CONFIG self._package_path = os.path.join(self._config.download_dir, package_path) def MaybeTweakAfterUnpackage(self): """Creates a CMakeLists.txt file for building the package.""" config = self._config cmakelists_path = os.path.join(self._package_path, 'CMakeLists.txt') if config.force and os.path.exists(cmakelists_path): os.unlink(cmakelists_path) if os.path.exists(cmakelists_path): return # Mongoose just builds a server, and does so nonstandard. # We want a library. There's only one file so pretty simple. print '>>> Creating CMakeLists.txt as %s' % cmakelists_path with open(cmakelists_path, 'w') as f: f.write('cmake_minimum_required (VERSION 2.6)\n') f.write('project (Mongoose)\n') f.write('add_library(mongoose STATIC mongoose.c)\n') f.write('add_definitions( -DNO_CGI -U__STDC_FORMAT_MACROS )\n') def Install(self): """Copies headers and libraries to install the package.""" config = self._config include_dir = os.path.join(config.abs_install_dir, 'include', 'mongoose') if not os.path.exists(include_dir): os.makedirs(include_dir) shutil.copy(os.path.join(self._package_path, 'mongoose.h'), include_dir) libdir = os.path.join(config.abs_install_dir, 'lib') if not os.path.exists(libdir): os.makedirs(libdir) if config.port != WINDOWS_PLATFORM: shutil.copy(os.path.join(self._package_path, 'libmongoose.a'), libdir) else: for ext in ['lib', 'pdb']: shutil.copy(os.path.join(self._package_path, 'mongoose.%s' % ext), libdir) class JsonCppPackageInstaller(PackageInstaller): """Custom installer for the JsonCpp package.""" def __init__(self, config, url): """Standard PackageInstaller initializer.""" super(JsonCppPackageInstaller, self).__init__(config, url) self._config_type = CMAKE_CONFIG def MaybeTweakAfterUnpackage(self): """Creates a CMakeLists.txt to build the package.""" config = self._config os.chdir(self._package_path) if config.force and os.path.exists('CMakeLists.txt'): os.unlink('CMakeLists.txt') if os.path.exists('CMakeLists.txt'): return if config.build_packages: allfiles = '' src_path = os.path.join('src', 'lib_json') for elem in glob.glob('%s/*.cpp' % src_path): allfiles = '%s "%s"' % (allfiles, elem) print '>>> Creating CMakeLists.txt' with open('CMakeLists.txt', 'w') as f: f.write('cmake_minimum_required (VERSION 2.6)\n') f.write('project (JsonCpp)\n') f.write('INCLUDE_DIRECTORIES(./include src/lib_json)\n') f.write('add_library(jsoncpp STATIC %s)\n' % allfiles) def Install(self): """Copies the libraries nad header files to install the package.""" config = self._config print '>>> Installing %s' % self._package_name PackageInstaller.CopyAllFiles( os.path.join(self._package_path, 'include'), os.path.join(config.abs_install_dir, 'include')) libdir = os.path.join(config.abs_install_dir, 'lib') if not os.path.exists(libdir): os.makedirs(libdir) if config.port != WINDOWS_PLATFORM: shutil.copy('libjsoncpp.a', libdir) else: for ext in ['lib', 'pdb']: shutil.copy('jsoncpp.%s' % ext, libdir) class CMakeExeInstaller(PackageInstaller): """Installs CMake under Windows from initialization executable.""" def __init__(self, config, url): """Standard PackageInstaller initializer.""" super(CMakeExeInstaller, self).__init__(config, url, package_name='ignore') def Unpackage(self): return def Configure(self): return def Compile(self): return def Install(self): """Runs installer to install CMake (on the system).""" config = self._config if not config.force: if PackageInstaller._VerifyProgram('cmake', '--version'): print 'Already have CMake' return print 'Installing CMake' download_dir = config.download_dir exe_filename = self._archive_file os.chdir(download_dir) # This is a self-installing .exe file PackageInstaller.RunOrDie( exe_filename, 'Failed to install CMake from %s.' % exe_filename) class IgnorePackageInstaller(PackageInstaller): """This package initializer does nothing.""" def __init__(self, config, url): """Standard PackageInstaller initializer.""" super(IgnorePackageInstaller, self).__init__( config, url, package_name='ignore') def Download(self): return def Unpackage(self): return def Configure(self): return def Compile(self): return def Install(self): return class OpenSslPackageInstaller(PackageInstaller): """Custom installer for the OpenSsl package.""" def __init__(self, config, url): """Standard PackageInstaller initializer.""" super(OpenSslPackageInstaller, self).__init__(config, url) if config.port == OSX_PLATFORM: self._extra_configure_flags = 'darwin64-x86_64-cc' elif platform.system() == 'Linux': self._extra_configure_flags = 'linux-%s' % platform.machine() else: self._extra_configure_flags = 'gcc' def Configure(self): # TODO(user): 20130626 # These artifacts are probably not even needed. Investigate for a # future release. print 'NOTE for Google APIs Client Library for C++ Installer:' print ' If this fails it might be because we guessed the wrong platform.' print ' Edit prepare_dependencies.py and notify us.' print ' See the README in the release for contact information.' super(OpenSslPackageInstaller, self).Configure() class GFlagsPackageInstaller(PackageInstaller): """Custom installer for the GFlags package.""" def __init__(self, config, url, package_name=None): """Standard PackageInstaller initializer.""" super(GFlagsPackageInstaller, self).__init__(config, url, package_name=package_name) self._archive_file = self._archive_file.replace('-no-svn-files', '') self._package_name = self._package_name.replace('-no-svn-files', '') self._package_path = self._package_path.replace('-no-svn-files', '') self._msbuild_args = '/p:Configuration=Release;Platform=x86' self._vc_upgrade_from_project_path = ( '%s\\vsprojects\\libgflags\\libgflags.vcproj' % self._package_path) self._vc_project_path = self._vc_upgrade_from_project_path.replace( '.vcproj', '.vcxproj') def Install(self): """Copis generated libs and headers into the install directory.""" config = self._config if config.compiler != VS_COMPILER: super(GFlagsPackageInstaller, self).Install() return print '>>> Installing %s' % self._package_name install_libdir = os.path.join(config.abs_install_dir, 'lib') install_includedir = os.path.join(config.abs_install_dir, 'include', 'gflags') if not os.path.exists(install_libdir): os.makedirs(install_libdir) if not os.path.exists(install_includedir): os.makedirs(install_includedir) PackageInstaller.CopyAllFiles( os.path.join(self._package_path, 'src', 'windows', 'gflags'), install_includedir) release_dir = os.path.join(self._package_path, 'vsprojects', 'libgflags', 'Release') for ext in ['lib', 'dll', 'pdb']: print 'renaming %s.%s' % (os.path.join(release_dir, 'libgflags'), ext) shutil.copyfile( '%s.%s' % (os.path.join(release_dir, 'libgflags'), ext), '%s.%s' % (os.path.join(install_libdir, 'libgflags'), ext)) class GMockPackageInstaller(PackageInstaller): """Custom installer for the GMock package.""" def __init__(self, config, url, package_name=None): """Standard PackageInstaller initializer. Args: config: (ConfigInfo) Configuration information. url: (string) The URL to download from. """ super(GMockPackageInstaller, self).__init__(config, url, package_name=package_name) def MaybeTweakAfterUnpackage(self): if self._config.compiler == VS_COMPILER: # But this wont actually build in visual studio because VC11 changed the # default number of variadic template parameters from 10 to 5 and we # need 10. So patch the build flags to force 10 cmake_utils_path = os.path.join( self._package_path, 'gtest', 'cmake', 'internal_utils.cmake') with open(cmake_utils_path, 'r') as f: text = f.read() inject_flags = '-D_VARIADIC_MAX=10' if text.find(inject_flags) < 0: insert_after = '-DSTRICT -DWIN32_LEAN_AND_MEAN' text = text.replace(insert_after, '%s %s' % ( insert_after, inject_flags)) with open(cmake_utils_path, 'w') as f: f.write(text) def Configure(self): return def Compile(self): return def Install(self): # GMock needs to be installed in the build tree (i.e. the root_dir/src # because that's what it wants. gmock_path = os.path.join(self._config.abs_root_dir, 'src', 'gmock') if self._config.force and os.path.exists(gmock_path): shutil.rmtree(gmock_path) if os.path.exists(gmock_path): return shutil.copytree(self._package_path, gmock_path) class GLogPackageInstaller(PackageInstaller): """Custom installer for the GLog package.""" def __init__(self, config, url, package_name=None): """Standard PackageInstaller initializer. Args: config: (ConfigInfo) Configuration information. url: (string) The URL to download from. """ super(GLogPackageInstaller, self).__init__(config, url, package_name=package_name) self._msbuild_args = '/p:Configuration=Release;Platform=x86' self._vc_upgrade_from_project_path = ( '%s\\vsprojects\\libglog\\libglog.vcproj' % self._package_path) self._vc_project_path = ( '%s\\vsprojects\\libglog\\libglog.vcxproj' % self._package_path) def MaybeTweakAfterUnpackage(self): """Tweaks a header file declaration under windows so it compiles.""" super(GLogPackageInstaller, self).MaybeTweakAfterUnpackage() remove_cygwin_paths = [ os.path.join(self._package_path, 'src', 'googletest.h'), os.path.join(self._package_path, 'src', 'utilities.cc') ] for change_path in remove_cygwin_paths: changed = False with open(change_path, 'r') as f: old_text = f.read() # The source couple windows and cygwin together for some reason, # but that doesnt compile. CYGWIN appears to work if you take these # out (it will use pthreads instead of the windows API). text = old_text.replace('defined(OS_WINDOWS) || defined(OS_CYGWIN)', 'defined(OS_WINDOWS)') text = text.replace('defined OS_WINDOWS || defined OS_CYGWIN', 'defined(OS_WINDOWS)') changed = old_text != text if changed: with open(change_path, 'w') as f: f.write(text) print 'Hacked %s' % change_path logging_h_path = os.path.join( self._package_path, 'src', 'windows', 'glog', 'logging.h') changed = False with open(logging_h_path, 'r') as f: old_text = f.read() text = old_text.replace('class LogStreamBuf', 'class GOOGLE_GLOG_DLL_DECL LogStreamBuf') changed = old_text != text if changed: with open(logging_h_path, 'w') as f: f.write(text) print 'Hacked %s' % logging_h_path def Install(self): """Overrides install to copy the generated headers and libs.""" if self._config.port != WINDOWS_PLATFORM: super(GLogPackageInstaller, self).Install() return config = self._config install_libdir = os.path.join(config.abs_install_dir, 'lib') install_includedir = os.path.join( config.abs_install_dir, 'include', 'glog') print '>>> Installing %s' % self._package_name if not os.path.exists(install_libdir): os.makedirs(install_libdir) if not os.path.exists(install_includedir): os.makedirs(install_includedir) PackageInstaller.CopyAllFiles( os.path.join(self._package_path, 'src', 'windows', 'glog'), install_includedir) release_dir = os.path.join( self._package_path, 'vsprojects', 'libglog', 'Release') for ext in ['lib', 'dll', 'pdb']: shutil.copyfile('%s.%s' % (os.path.join(release_dir, 'libglog'), ext), '%s.%s' % (os.path.join(install_libdir, 'libglog'), ext)) class CurlPackageInstaller(PackageInstaller): def __init__(self, config, url): if config.compiler == VS_COMPILER: config_type = CMAKE_CONFIG else: config_type = CONFIGURE_CONFIG super(CurlPackageInstaller, self).__init__( config, url, config_type=config_type) class Installer(object): """Acquires, builds, and installs dependencies for the SDK.""" def __init__(self, config, restricted_package_names): """Set up variables from flags. Exit on failure. Args: config: (ConfigInfo) Configuraton options. restricted_package_names: (Array) Subset of package names to install. """ print 'Initializing....' # If non-empty then just prepare these packages. # The entries here are keys in url_map self._restricted_packages = restricted_package_names self._url_map = {} if config.port == WINDOWS_PLATFORM or config.port == CYGWIN_PLATFORM: self._url_map.update({ # Use CMake as our build system for the libraries and some deps 'cmake': (CMakeExeInstaller( config, 'http://www.cmake.org/files/v3.1/cmake-3.1.1-win32-x86.exe')), 'openssl': (IgnorePackageInstaller(config, 'ignoring_openssl')), }) else: self._url_map.update({ # Use CMake as our build system for the libraries and some deps 'cmake': (PackageInstaller( config, 'http://www.cmake.org/files/v3.1/cmake-3.1.1.tar.gz', config_type=CONFIGURE_CONFIG)), # This is used both for curl https support and # the OpenSslCodec library for the OpenSslCodec for data encryption. # The OpenSslCodec is not requird so if you get an https transport # from somewhere else then you do not need this dependency. 'openssl': (OpenSslPackageInstaller( config, 'https://www.openssl.org/source/openssl-1.1.0e.tar.gz')), }) self._url_map.update({ # GFlags is only used for some examples. # Only used for tests and samples. 'gflags': (GFlagsPackageInstaller( config, 'https://github.com/gflags/gflags/archive/v2.2.0.tar.gz', 'gflags-2.2.0')), # GLog is the logging mechanism used through the client API 'glog': (GLogPackageInstaller( config, 'https://github.com/google/glog/archive/v0.3.4.tar.gz', 'glog-0.3.4')), # GMock (and included GTest) are only used for tests, not runtime # Only used for tests. 'gmock': (GMockPackageInstaller( config, 'https://github.com/google/googlemock/archive/release-1.7.0.tar.gz', 'googlemock-release-1.7.0')), # For now we use JsonCpp for JSON support in the Client Service Layer # and other places where we process JSON encoded data. 'jsoncpp': (JsonCppPackageInstaller( config, 'http://downloads.sourceforge.net/project/jsoncpp' '/jsoncpp/0.5.0/jsoncpp-src-0.5.0.tar.gz')), # Mongoose is used as webserver for samples. # The ownership and license style seems to keep changing, so we do not # download it by default. 'mongoose': (MongoosePackageInstaller( config, 'https://github.com/cesanta/mongoose/archive/6.7.zip', 'mongoose-6.7')), 'curl': (CurlPackageInstaller( config, 'https://github.com/curl/curl/releases/download/curl-7_54_0/curl-7.54.0.tar.gz')), }) # make sure cmake occurs first since others may depend on it if not self._restricted_packages: self._restricted_packages = self._url_map.keys() ordered_packages = ['cmake', 'openssl', 'glog'] for p in ordered_packages: self._restricted_packages.remove(p) self._restricted_packages = ordered_packages + self._restricted_packages def ProcessDependencyOrDie(self, name): """Process a single dependency. Args: name: (string) The name of the dependency to process. """ value = self._url_map.get(name) if not value: print 'Unknown package "%s"' % name sys.exit(1) value.Process() def Run(self): """Run the installer. Returns: Packages that were processed. """ restricts = self._restricted_packages # Attempt to process each of the requested packages. for key in restricts: self.ProcessDependencyOrDie(key) return restricts if __name__ == '__main__': config_info = ConfigInfo(os.getcwd(), sys.argv) restricted_packages = [] try: opts, restricted_packages = getopt.getopt( sys.argv[1:], 'bdi', ['download_dir=', 'install_dir=', 'force']) config_info.SetOptions(opts) except getopt.GetoptError: print ('%s: [-b] [-d] [-i]' % sys.argv[0] + '[--download_dir=<path>] [--install_dir=<path>] [--force]') sys.exit(1) installer = Installer(config_info, restricted_packages) processed_packages = installer.Run() print '\nFinished processing %s' % str(processed_packages) <file_sep>/service_apis/youtube/google/youtube_api/activity_content_details.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Description: // Supports core YouTube features, such as uploading videos, creating and managing playlists, searching for content, and much more. // Classes: // ActivityContentDetails // Documentation: // https://developers.google.com/youtube/v3 #include "google/youtube_api/activity_content_details.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/activity_content_details_bulletin.h" #include "google/youtube_api/activity_content_details_channel_item.h" #include "google/youtube_api/activity_content_details_comment.h" #include "google/youtube_api/activity_content_details_favorite.h" #include "google/youtube_api/activity_content_details_like.h" #include "google/youtube_api/activity_content_details_playlist_item.h" #include "google/youtube_api/activity_content_details_promoted_item.h" #include "google/youtube_api/activity_content_details_recommendation.h" #include "google/youtube_api/activity_content_details_social.h" #include "google/youtube_api/activity_content_details_subscription.h" #include "google/youtube_api/activity_content_details_upload.h" #include <string> #include "googleapis/strings/strcat.h" namespace google_youtube_api { using namespace googleapis; // Object factory method (static). ActivityContentDetails* ActivityContentDetails::New() { return new client::JsonCppCapsule<ActivityContentDetails>; } // Standard immutable constructor. ActivityContentDetails::ActivityContentDetails(const Json::Value& storage) : client::JsonCppData(storage) { } // Standard mutable constructor. ActivityContentDetails::ActivityContentDetails(Json::Value* storage) : client::JsonCppData(storage) { } // Standard destructor. ActivityContentDetails::~ActivityContentDetails() { } // Properties. const ActivityContentDetailsBulletin ActivityContentDetails::get_bulletin() const { const Json::Value& storage = Storage("bulletin"); return client::JsonValueToCppValueHelper<ActivityContentDetailsBulletin >(storage); } ActivityContentDetailsBulletin ActivityContentDetails::mutable_bulletin() { Json::Value* storage = MutableStorage("bulletin"); return client::JsonValueToMutableCppValueHelper<ActivityContentDetailsBulletin >(storage); } const ActivityContentDetailsChannelItem ActivityContentDetails::get_channel_item() const { const Json::Value& storage = Storage("channelItem"); return client::JsonValueToCppValueHelper<ActivityContentDetailsChannelItem >(storage); } ActivityContentDetailsChannelItem ActivityContentDetails::mutable_channelItem() { Json::Value* storage = MutableStorage("channelItem"); return client::JsonValueToMutableCppValueHelper<ActivityContentDetailsChannelItem >(storage); } const ActivityContentDetailsComment ActivityContentDetails::get_comment() const { const Json::Value& storage = Storage("comment"); return client::JsonValueToCppValueHelper<ActivityContentDetailsComment >(storage); } ActivityContentDetailsComment ActivityContentDetails::mutable_comment() { Json::Value* storage = MutableStorage("comment"); return client::JsonValueToMutableCppValueHelper<ActivityContentDetailsComment >(storage); } const ActivityContentDetailsFavorite ActivityContentDetails::get_favorite() const { const Json::Value& storage = Storage("favorite"); return client::JsonValueToCppValueHelper<ActivityContentDetailsFavorite >(storage); } ActivityContentDetailsFavorite ActivityContentDetails::mutable_favorite() { Json::Value* storage = MutableStorage("favorite"); return client::JsonValueToMutableCppValueHelper<ActivityContentDetailsFavorite >(storage); } const ActivityContentDetailsLike ActivityContentDetails::get_like() const { const Json::Value& storage = Storage("like"); return client::JsonValueToCppValueHelper<ActivityContentDetailsLike >(storage); } ActivityContentDetailsLike ActivityContentDetails::mutable_like() { Json::Value* storage = MutableStorage("like"); return client::JsonValueToMutableCppValueHelper<ActivityContentDetailsLike >(storage); } const ActivityContentDetailsPlaylistItem ActivityContentDetails::get_playlist_item() const { const Json::Value& storage = Storage("playlistItem"); return client::JsonValueToCppValueHelper<ActivityContentDetailsPlaylistItem >(storage); } ActivityContentDetailsPlaylistItem ActivityContentDetails::mutable_playlistItem() { Json::Value* storage = MutableStorage("playlistItem"); return client::JsonValueToMutableCppValueHelper<ActivityContentDetailsPlaylistItem >(storage); } const ActivityContentDetailsPromotedItem ActivityContentDetails::get_promoted_item() const { const Json::Value& storage = Storage("promotedItem"); return client::JsonValueToCppValueHelper<ActivityContentDetailsPromotedItem >(storage); } ActivityContentDetailsPromotedItem ActivityContentDetails::mutable_promotedItem() { Json::Value* storage = MutableStorage("promotedItem"); return client::JsonValueToMutableCppValueHelper<ActivityContentDetailsPromotedItem >(storage); } const ActivityContentDetailsRecommendation ActivityContentDetails::get_recommendation() const { const Json::Value& storage = Storage("recommendation"); return client::JsonValueToCppValueHelper<ActivityContentDetailsRecommendation >(storage); } ActivityContentDetailsRecommendation ActivityContentDetails::mutable_recommendation() { Json::Value* storage = MutableStorage("recommendation"); return client::JsonValueToMutableCppValueHelper<ActivityContentDetailsRecommendation >(storage); } const ActivityContentDetailsSocial ActivityContentDetails::get_social() const { const Json::Value& storage = Storage("social"); return client::JsonValueToCppValueHelper<ActivityContentDetailsSocial >(storage); } ActivityContentDetailsSocial ActivityContentDetails::mutable_social() { Json::Value* storage = MutableStorage("social"); return client::JsonValueToMutableCppValueHelper<ActivityContentDetailsSocial >(storage); } const ActivityContentDetailsSubscription ActivityContentDetails::get_subscription() const { const Json::Value& storage = Storage("subscription"); return client::JsonValueToCppValueHelper<ActivityContentDetailsSubscription >(storage); } ActivityContentDetailsSubscription ActivityContentDetails::mutable_subscription() { Json::Value* storage = MutableStorage("subscription"); return client::JsonValueToMutableCppValueHelper<ActivityContentDetailsSubscription >(storage); } const ActivityContentDetailsUpload ActivityContentDetails::get_upload() const { const Json::Value& storage = Storage("upload"); return client::JsonValueToCppValueHelper<ActivityContentDetailsUpload >(storage); } ActivityContentDetailsUpload ActivityContentDetails::mutable_upload() { Json::Value* storage = MutableStorage("upload"); return client::JsonValueToMutableCppValueHelper<ActivityContentDetailsUpload >(storage); } } // namespace google_youtube_api <file_sep>/src/googleapis/client/util/abstract_webserver.h /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ /* * @defgroup PlatformLayerWebServer Platform Layer - Embedded Web Server * * The embedded webserver module is provided by the Plaform Layer rather * than the Trnasport Layer were you might otherwise expect it. This is * because we are not really embracing it as a core product feature. It is * only here to support providing interfaces to iteractt with embedded * HTTP servers and for writing tests. * * The request/response abstraction in this module is distinctly different * (and not compatible with) the HttpRequest interface core to the * Transport Layer. The transport layer is designed around the needs of * clients. The embedded web server is for servers. Because the focal point * of the SDK is strictly for clients, we are keeping the focus and viewpoints * more stictly separated. */ #ifndef GOOGLEAPIS_UTIL_ABSTRACT_WEBSERVER_H_ #define GOOGLEAPIS_UTIL_ABSTRACT_WEBSERVER_H_ #include <memory> #include <string> using std::string; #include <utility> #include <vector> #include "googleapis/client/util/status.h" #include "googleapis/client/util/uri_utils.h" #include "googleapis/base/callback.h" #include "googleapis/base/macros.h" namespace googleapis { namespace client { /* * Abstract class for responses to WebServerRequests into the * AbstractWebServer * @ingroup PlatformLayerWebServer * * This is different from the HttpResponse class in the transport layer * which are client-side responses. These are server side responses. * * Responses are owned and created by WebServerRequest. */ class WebServerResponse { public: WebServerResponse() {} virtual ~WebServerResponse() {} /* * Respond with a text/html content type and body. * * @param[in] http_code The HTTP status code to send. * @param[in] body The payload can be empty. * * @return ok or reason for failure. */ googleapis::util::Status SendHtml(int http_code, const string& body) { return SendReply("text/html", http_code, body); } /* * Respond with a text/plain content type and body. * * @param[in] http_code The HTTP status code to send. * @param[in] body The payload can be empty. * * @return ok or reason for failure. */ googleapis::util::Status SendText(int http_code, const string& body) { return SendReply("text/plain", http_code, body); } /* * Respond with a redirect to another url. * * @param[in] http_code The HTTP status code to send (e.g. 307). * @param[in] url The url to redirect to. * * @return ok or reason for failure. */ virtual googleapis::util::Status SendRedirect(int http_code, const string& url); /* * Respond with an specified content type and body. * * @param[in] content_type The MIME content type of the body. * @param[in] http_code The HTTP status code to send. * @param[in] body The payload can be empty. * * @return ok or reason for failure. */ virtual googleapis::util::Status SendReply( const string& content_type, int http_code, const string& body) = 0; /* * Adds a custom header to the repsonse. * * Content-Type, Content-Length and Location headers are automatically added. * This will not check the header names or values. * * @param[in] name The name of header to add. * @param[in] value The value of the header. */ virtual googleapis::util::Status AddHeader( const string& name, const string& value) = 0; /* * Adds a custom cookie to the repsonse. * * This will not check the cookie names or values. * * @param[in] name The name of header to add. * @param[in] value The value of the header. */ virtual googleapis::util::Status AddCookie( const string& name, const string& value) = 0; private: DISALLOW_COPY_AND_ASSIGN(WebServerResponse); }; /* * Abstract class for invocations into the AbstractWebServer * @ingroup PlatformLayerWebServer * * This is different from the HttpRequest class in the transport layer * which are client-side requests. These are server side requests. * * Requests are created by the AbstractWebServer when it receives an * invocation. */ class WebServerRequest { public: /* * Standard constructor. * * @param[in] method The HTTP method called (e.g. GET). * @param[in] url The url that was invoked. * @param[in] response_storage The repsonse object to bind to the request. */ WebServerRequest( const string& method, const string& url, WebServerResponse* response_storage); /* * Standard destructor. */ virtual ~WebServerRequest(); const string& method() const { return method_; } const ParsedUrl& parsed_url() const { return parsed_url_; } WebServerResponse* response() const { return response_.get(); } virtual bool GetCookieValue(const char* key, string* value) const = 0; virtual bool GetHeaderValue(const char* key, string* value) const = 0; private: string method_; ParsedUrl parsed_url_; std::unique_ptr<WebServerResponse> response_; }; /* * A minimal abstract interface for embedded webservers. * @ingroup PlatformLayerWebServer * * This is only an abstract interface. You must supply * your own implementation and use this class to adapt it. The interface * is only intended to provide some library code and sample code that integrate * with an embedded web server without explicitly depending on any particular * implementation. * * Note that this interface does not accomodate POST requests at this time, * but the library does not need it as a client -- this abstractionis not * intended to be used for implementing cloud services. */ class AbstractWebServer { public: /* * Used to register a callback on particular URIs or trees. * * @param[in] request for the request being processed. * @return ok or reason for failure. */ typedef ResultCallback1< googleapis::util::Status, WebServerRequest*> PathHandler; /* * Constructs an http server on the given port * * @param[in] port Should be non-0. */ explicit AbstractWebServer(int port); /* * Standard destructor. */ virtual ~AbstractWebServer(); /* * Returns the port bound in the constructor. */ int port() const { return port_; } /* * Starts the server. * * @return ok or reason for error. */ googleapis::util::Status Startup(); /* * Stops the server. * * @return ok or reason for error. */ void Shutdown(); /* * Returns URL into this server for the given path. * * @param[in] use_localhost If true use 'localhost' rather than the hostname. * @param[in] path The path part of the url to build. */ string MakeEndpointUrl(bool use_localhost, const string& path) const; /* * Inject handler for path. * * @param[in] path The path to intercept with this handler. * @param[in] handler A repeatable callback. Ownership is passed. * * This is called by the default DoHandleUrl method. */ void AddPathHandler(const string& path, PathHandler* handler); /* * Looks up added PathHandler that matches path. * * Searches in the order they were added. * * @param[in] request The request to lookup. * @return path handler or NULL if one could not be found. */ PathHandler* FindPathHandler(WebServerRequest* request) const; /* * Returns the protocol part of the url used by this webserver (e.g. 'https') */ virtual string url_protocol() const; protected: virtual googleapis::util::Status DoStartup() = 0; virtual void DoShutdown() = 0; /* * Handles inbound request. * * The base class method looks up a registered path handler that matches * the url path prefix. It returns a 404 if one isnt found. * * @param[in] request The request from the web server. */ virtual googleapis::util::Status DoHandleRequest(WebServerRequest* request); private: int port_; typedef std::pair<string, PathHandler*> Hook; std::vector<Hook> hooks_; DISALLOW_COPY_AND_ASSIGN(AbstractWebServer); }; } // namespace client } // namespace googleapis #endif // GOOGLEAPIS_UTIL_ABSTRACT_WEBSERVER_H_ <file_sep>/src/googleapis/client/auth/jwt_builder.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <string> using std::string; #include "googleapis/client/auth/jwt_builder.h" #include "googleapis/client/util/status.h" #include "googleapis/strings/escaping.h" #include "googleapis/strings/strcat.h" #include <openssl/bio.h> #include <openssl/buffer.h> #include <openssl/digest.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/pkcs12.h> #include <openssl/stack.h> #include <openssl/x509.h> namespace googleapis { namespace client { util::Status JwtBuilder::LoadPrivateKeyFromPkcs12Path( const string& path, string* result_key) { googleapis::util::Status status; result_key->clear(); OpenSSL_add_all_algorithms(); BIO* bio = BIO_new(BIO_s_mem()); EVP_PKEY* pkey = LoadPkeyFromP12Path(path.c_str()); if (!pkey) { status = StatusUnknown( StrCat("OpenSSL failed parsing PKCS#12 error=", ERR_get_error())); } else if (PEM_write_bio_PrivateKey( bio, pkey, nullptr, nullptr, 0, nullptr, nullptr) < 0) { status = StatusUnknown("OpenSSL Failed writing BIO memory output"); } if (status.ok()) { BUF_MEM *mem_ptr = nullptr; BIO_get_mem_ptr(bio, &mem_ptr); result_key->assign(mem_ptr->data, mem_ptr->length); // copies data out } BIO_free(bio); EVP_PKEY_free(pkey); return status; } void JwtBuilder::AppendAsBase64(const char* data, size_t size, string* to) { string encoded; strings::WebSafeBase64Escape( reinterpret_cast<const unsigned char*>(data), size, &encoded, false); to->append(encoded); } void JwtBuilder::AppendAsBase64(const string& from, string* to) { AppendAsBase64(from.data(), from.size(), to); } EVP_PKEY* JwtBuilder::LoadPkeyFromData(const StringPiece data) { BIO* bio = BIO_new_mem_buf(const_cast<char*>(data.data()), data.size()); EVP_PKEY* pkey = PEM_read_bio_PrivateKey( bio, nullptr, nullptr, const_cast<char*>("notasecret")); if (pkey == nullptr) { char buffer[128]; ERR_error_string(ERR_get_error(), buffer); LOG(ERROR) << "OpenSslError reading private key: " << buffer; } BIO_free(bio); return pkey; } EVP_PKEY* JwtBuilder::LoadPkeyFromP12Path(const char* pkcs12_key_path) { // OpenSSL_add_all_algorithms(); X509 *cert = nullptr; STACK_OF(X509) *ca = nullptr; PKCS12 *p12; FILE* fp = fopen(pkcs12_key_path, "rb"); CHECK(fp != nullptr); p12 = d2i_PKCS12_fp(fp, nullptr); fclose(fp); if (!p12) { googleapis::util::Status status = StatusUnknown( StrCat("OpenSSL failed reading PKCS#12 error=", ERR_get_error())); LOG(ERROR) << status.error_message(); return nullptr; } EVP_PKEY* pkey = nullptr; int ok = PKCS12_parse(p12, "notasecret", &pkey, &cert, &ca); PKCS12_free(p12); if (cert) { X509_free(cert); } if (ca) { sk_X509_pop_free(ca, X509_free); } CHECK(ok); return pkey; } util::Status JwtBuilder::MakeJwtUsingEvp( const string& claims, EVP_PKEY* pkey, string* jwt) { const char* plain_header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}"; string data_to_sign; AppendAsBase64(plain_header, &data_to_sign); data_to_sign.append("."); AppendAsBase64(claims, &data_to_sign); googleapis::util::Status status; EVP_MD_CTX ctx; EVP_SignInit(&ctx, EVP_sha256()); EVP_SignUpdate(&ctx, data_to_sign.c_str(), data_to_sign.size()); unsigned int buffer_size = EVP_PKEY_size(pkey); std::unique_ptr<char[]> buffer(new char[buffer_size]); if (EVP_SignFinal( &ctx, reinterpret_cast<unsigned char*>(buffer.get()), &buffer_size, pkey) == 0) { status = StatusInternalError( StrCat("Failed signing JWT. error=", ERR_get_error())); } EVP_MD_CTX_cleanup(&ctx); if (!status.ok()) return status; jwt->swap(data_to_sign); jwt->append("."); AppendAsBase64(buffer.get(), buffer_size, jwt); return StatusOk(); } } // namespace client } // namespace googleapis <file_sep>/service_apis/youtube/google/youtube_api/activity_content_details_promoted_item.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_ACTIVITY_CONTENT_DETAILS_PROMOTED_ITEM_H_ #define GOOGLE_YOUTUBE_API_ACTIVITY_CONTENT_DETAILS_PROMOTED_ITEM_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Details about a resource which is being promoted. * * @ingroup DataObject */ class ActivityContentDetailsPromotedItem : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static ActivityContentDetailsPromotedItem* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ActivityContentDetailsPromotedItem(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ActivityContentDetailsPromotedItem(Json::Value* storage); /** * Standard destructor. */ virtual ~ActivityContentDetailsPromotedItem(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::ActivityContentDetailsPromotedItem</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::ActivityContentDetailsPromotedItem"); } /** * Determine if the '<code>adTag</code>' attribute was set. * * @return true if the '<code>adTag</code>' attribute was set. */ bool has_ad_tag() const { return Storage().isMember("adTag"); } /** * Clears the '<code>adTag</code>' attribute. */ void clear_ad_tag() { MutableStorage()->removeMember("adTag"); } /** * Get the value of the '<code>adTag</code>' attribute. */ const StringPiece get_ad_tag() const { const Json::Value& v = Storage("adTag"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>adTag</code>' attribute. * * The URL the client should fetch to request a promoted item. * * @param[in] value The new value. */ void set_ad_tag(const StringPiece& value) { *MutableStorage("adTag") = value.data(); } /** * Determine if the '<code>clickTrackingUrl</code>' attribute was set. * * @return true if the '<code>clickTrackingUrl</code>' attribute was set. */ bool has_click_tracking_url() const { return Storage().isMember("clickTrackingUrl"); } /** * Clears the '<code>clickTrackingUrl</code>' attribute. */ void clear_click_tracking_url() { MutableStorage()->removeMember("clickTrackingUrl"); } /** * Get the value of the '<code>clickTrackingUrl</code>' attribute. */ const StringPiece get_click_tracking_url() const { const Json::Value& v = Storage("clickTrackingUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>clickTrackingUrl</code>' attribute. * * The URL the client should ping to indicate that the user clicked through on * this promoted item. * * @param[in] value The new value. */ void set_click_tracking_url(const StringPiece& value) { *MutableStorage("clickTrackingUrl") = value.data(); } /** * Determine if the '<code>creativeViewUrl</code>' attribute was set. * * @return true if the '<code>creativeViewUrl</code>' attribute was set. */ bool has_creative_view_url() const { return Storage().isMember("creativeViewUrl"); } /** * Clears the '<code>creativeViewUrl</code>' attribute. */ void clear_creative_view_url() { MutableStorage()->removeMember("creativeViewUrl"); } /** * Get the value of the '<code>creativeViewUrl</code>' attribute. */ const StringPiece get_creative_view_url() const { const Json::Value& v = Storage("creativeViewUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>creativeViewUrl</code>' attribute. * * The URL the client should ping to indicate that the user was shown this * promoted item. * * @param[in] value The new value. */ void set_creative_view_url(const StringPiece& value) { *MutableStorage("creativeViewUrl") = value.data(); } /** * Determine if the '<code>ctaType</code>' attribute was set. * * @return true if the '<code>ctaType</code>' attribute was set. */ bool has_cta_type() const { return Storage().isMember("ctaType"); } /** * Clears the '<code>ctaType</code>' attribute. */ void clear_cta_type() { MutableStorage()->removeMember("ctaType"); } /** * Get the value of the '<code>ctaType</code>' attribute. */ const StringPiece get_cta_type() const { const Json::Value& v = Storage("ctaType"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>ctaType</code>' attribute. * * The type of call-to-action, a message to the user indicating action that * can be taken. * * @param[in] value The new value. */ void set_cta_type(const StringPiece& value) { *MutableStorage("ctaType") = value.data(); } /** * Determine if the '<code>customCtaButtonText</code>' attribute was set. * * @return true if the '<code>customCtaButtonText</code>' attribute was set. */ bool has_custom_cta_button_text() const { return Storage().isMember("customCtaButtonText"); } /** * Clears the '<code>customCtaButtonText</code>' attribute. */ void clear_custom_cta_button_text() { MutableStorage()->removeMember("customCtaButtonText"); } /** * Get the value of the '<code>customCtaButtonText</code>' attribute. */ const StringPiece get_custom_cta_button_text() const { const Json::Value& v = Storage("customCtaButtonText"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>customCtaButtonText</code>' attribute. * * The custom call-to-action button text. If specified, it will override the * default button text for the cta_type. * * @param[in] value The new value. */ void set_custom_cta_button_text(const StringPiece& value) { *MutableStorage("customCtaButtonText") = value.data(); } /** * Determine if the '<code>descriptionText</code>' attribute was set. * * @return true if the '<code>descriptionText</code>' attribute was set. */ bool has_description_text() const { return Storage().isMember("descriptionText"); } /** * Clears the '<code>descriptionText</code>' attribute. */ void clear_description_text() { MutableStorage()->removeMember("descriptionText"); } /** * Get the value of the '<code>descriptionText</code>' attribute. */ const StringPiece get_description_text() const { const Json::Value& v = Storage("descriptionText"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>descriptionText</code>' attribute. * * The text description to accompany the promoted item. * * @param[in] value The new value. */ void set_description_text(const StringPiece& value) { *MutableStorage("descriptionText") = value.data(); } /** * Determine if the '<code>destinationUrl</code>' attribute was set. * * @return true if the '<code>destinationUrl</code>' attribute was set. */ bool has_destination_url() const { return Storage().isMember("destinationUrl"); } /** * Clears the '<code>destinationUrl</code>' attribute. */ void clear_destination_url() { MutableStorage()->removeMember("destinationUrl"); } /** * Get the value of the '<code>destinationUrl</code>' attribute. */ const StringPiece get_destination_url() const { const Json::Value& v = Storage("destinationUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>destinationUrl</code>' attribute. * * The URL the client should direct the user to, if the user chooses to visit * the advertiser's website. * * @param[in] value The new value. */ void set_destination_url(const StringPiece& value) { *MutableStorage("destinationUrl") = value.data(); } /** * Determine if the '<code>forecastingUrl</code>' attribute was set. * * @return true if the '<code>forecastingUrl</code>' attribute was set. */ bool has_forecasting_url() const { return Storage().isMember("forecastingUrl"); } /** * Clears the '<code>forecastingUrl</code>' attribute. */ void clear_forecasting_url() { MutableStorage()->removeMember("forecastingUrl"); } /** * Get a reference to the value of the '<code>forecastingUrl</code>' * attribute. */ const client::JsonCppArray<string > get_forecasting_url() const { const Json::Value& storage = Storage("forecastingUrl"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>forecastingUrl</code>' * property. * * The list of forecasting URLs. The client should ping all of these URLs when * a promoted item is not available, to indicate that a promoted item could * have been shown. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_forecastingUrl() { Json::Value* storage = MutableStorage("forecastingUrl"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>impressionUrl</code>' attribute was set. * * @return true if the '<code>impressionUrl</code>' attribute was set. */ bool has_impression_url() const { return Storage().isMember("impressionUrl"); } /** * Clears the '<code>impressionUrl</code>' attribute. */ void clear_impression_url() { MutableStorage()->removeMember("impressionUrl"); } /** * Get a reference to the value of the '<code>impressionUrl</code>' attribute. */ const client::JsonCppArray<string > get_impression_url() const { const Json::Value& storage = Storage("impressionUrl"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>impressionUrl</code>' * property. * * The list of impression URLs. The client should ping all of these URLs to * indicate that the user was shown this promoted item. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_impressionUrl() { Json::Value* storage = MutableStorage("impressionUrl"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>videoId</code>' attribute was set. * * @return true if the '<code>videoId</code>' attribute was set. */ bool has_video_id() const { return Storage().isMember("videoId"); } /** * Clears the '<code>videoId</code>' attribute. */ void clear_video_id() { MutableStorage()->removeMember("videoId"); } /** * Get the value of the '<code>videoId</code>' attribute. */ const StringPiece get_video_id() const { const Json::Value& v = Storage("videoId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>videoId</code>' attribute. * * The ID that YouTube uses to uniquely identify the promoted video. * * @param[in] value The new value. */ void set_video_id(const StringPiece& value) { *MutableStorage("videoId") = value.data(); } private: void operator=(const ActivityContentDetailsPromotedItem&); }; // ActivityContentDetailsPromotedItem } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_ACTIVITY_CONTENT_DETAILS_PROMOTED_ITEM_H_ <file_sep>/service_apis/youtube/google/youtube_api/live_broadcast_snippet.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_LIVE_BROADCAST_SNIPPET_H_ #define GOOGLE_YOUTUBE_API_LIVE_BROADCAST_SNIPPET_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/thumbnail_details.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * No description provided. * * @ingroup DataObject */ class LiveBroadcastSnippet : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static LiveBroadcastSnippet* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveBroadcastSnippet(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveBroadcastSnippet(Json::Value* storage); /** * Standard destructor. */ virtual ~LiveBroadcastSnippet(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::LiveBroadcastSnippet</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::LiveBroadcastSnippet"); } /** * Determine if the '<code>actualEndTime</code>' attribute was set. * * @return true if the '<code>actualEndTime</code>' attribute was set. */ bool has_actual_end_time() const { return Storage().isMember("actualEndTime"); } /** * Clears the '<code>actualEndTime</code>' attribute. */ void clear_actual_end_time() { MutableStorage()->removeMember("actualEndTime"); } /** * Get the value of the '<code>actualEndTime</code>' attribute. */ client::DateTime get_actual_end_time() const { const Json::Value& storage = Storage("actualEndTime"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>actualEndTime</code>' attribute. * * The date and time that the broadcast actually ended. This information is * only available once the broadcast's state is complete. The value is * specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. * * @param[in] value The new value. */ void set_actual_end_time(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("actualEndTime")); } /** * Determine if the '<code>actualStartTime</code>' attribute was set. * * @return true if the '<code>actualStartTime</code>' attribute was set. */ bool has_actual_start_time() const { return Storage().isMember("actualStartTime"); } /** * Clears the '<code>actualStartTime</code>' attribute. */ void clear_actual_start_time() { MutableStorage()->removeMember("actualStartTime"); } /** * Get the value of the '<code>actualStartTime</code>' attribute. */ client::DateTime get_actual_start_time() const { const Json::Value& storage = Storage("actualStartTime"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>actualStartTime</code>' attribute. * * The date and time that the broadcast actually started. This information is * only available once the broadcast's state is live. The value is specified * in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. * * @param[in] value The new value. */ void set_actual_start_time(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("actualStartTime")); } /** * Determine if the '<code>channelId</code>' attribute was set. * * @return true if the '<code>channelId</code>' attribute was set. */ bool has_channel_id() const { return Storage().isMember("channelId"); } /** * Clears the '<code>channelId</code>' attribute. */ void clear_channel_id() { MutableStorage()->removeMember("channelId"); } /** * Get the value of the '<code>channelId</code>' attribute. */ const StringPiece get_channel_id() const { const Json::Value& v = Storage("channelId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>channelId</code>' attribute. * * The ID that YouTube uses to uniquely identify the channel that is * publishing the broadcast. * * @param[in] value The new value. */ void set_channel_id(const StringPiece& value) { *MutableStorage("channelId") = value.data(); } /** * Determine if the '<code>description</code>' attribute was set. * * @return true if the '<code>description</code>' attribute was set. */ bool has_description() const { return Storage().isMember("description"); } /** * Clears the '<code>description</code>' attribute. */ void clear_description() { MutableStorage()->removeMember("description"); } /** * Get the value of the '<code>description</code>' attribute. */ const StringPiece get_description() const { const Json::Value& v = Storage("description"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>description</code>' attribute. * * The broadcast's description. As with the title, you can set this field by * modifying the broadcast resource or by setting the description field of the * corresponding video resource. * * @param[in] value The new value. */ void set_description(const StringPiece& value) { *MutableStorage("description") = value.data(); } /** * Determine if the '<code>isDefaultBroadcast</code>' attribute was set. * * @return true if the '<code>isDefaultBroadcast</code>' attribute was set. */ bool has_is_default_broadcast() const { return Storage().isMember("isDefaultBroadcast"); } /** * Clears the '<code>isDefaultBroadcast</code>' attribute. */ void clear_is_default_broadcast() { MutableStorage()->removeMember("isDefaultBroadcast"); } /** * Get the value of the '<code>isDefaultBroadcast</code>' attribute. */ bool get_is_default_broadcast() const { const Json::Value& storage = Storage("isDefaultBroadcast"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>isDefaultBroadcast</code>' attribute. * @param[in] value The new value. */ void set_is_default_broadcast(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("isDefaultBroadcast")); } /** * Determine if the '<code>liveChatId</code>' attribute was set. * * @return true if the '<code>liveChatId</code>' attribute was set. */ bool has_live_chat_id() const { return Storage().isMember("liveChatId"); } /** * Clears the '<code>liveChatId</code>' attribute. */ void clear_live_chat_id() { MutableStorage()->removeMember("liveChatId"); } /** * Get the value of the '<code>liveChatId</code>' attribute. */ const StringPiece get_live_chat_id() const { const Json::Value& v = Storage("liveChatId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>liveChatId</code>' attribute. * * The id of the live chat for this broadcast. * * @param[in] value The new value. */ void set_live_chat_id(const StringPiece& value) { *MutableStorage("liveChatId") = value.data(); } /** * Determine if the '<code>publishedAt</code>' attribute was set. * * @return true if the '<code>publishedAt</code>' attribute was set. */ bool has_published_at() const { return Storage().isMember("publishedAt"); } /** * Clears the '<code>publishedAt</code>' attribute. */ void clear_published_at() { MutableStorage()->removeMember("publishedAt"); } /** * Get the value of the '<code>publishedAt</code>' attribute. */ client::DateTime get_published_at() const { const Json::Value& storage = Storage("publishedAt"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>publishedAt</code>' attribute. * * The date and time that the broadcast was added to YouTube's live broadcast * schedule. The value is specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) * format. * * @param[in] value The new value. */ void set_published_at(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("publishedAt")); } /** * Determine if the '<code>scheduledEndTime</code>' attribute was set. * * @return true if the '<code>scheduledEndTime</code>' attribute was set. */ bool has_scheduled_end_time() const { return Storage().isMember("scheduledEndTime"); } /** * Clears the '<code>scheduledEndTime</code>' attribute. */ void clear_scheduled_end_time() { MutableStorage()->removeMember("scheduledEndTime"); } /** * Get the value of the '<code>scheduledEndTime</code>' attribute. */ client::DateTime get_scheduled_end_time() const { const Json::Value& storage = Storage("scheduledEndTime"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>scheduledEndTime</code>' attribute. * * The date and time that the broadcast is scheduled to end. The value is * specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. * * @param[in] value The new value. */ void set_scheduled_end_time(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("scheduledEndTime")); } /** * Determine if the '<code>scheduledStartTime</code>' attribute was set. * * @return true if the '<code>scheduledStartTime</code>' attribute was set. */ bool has_scheduled_start_time() const { return Storage().isMember("scheduledStartTime"); } /** * Clears the '<code>scheduledStartTime</code>' attribute. */ void clear_scheduled_start_time() { MutableStorage()->removeMember("scheduledStartTime"); } /** * Get the value of the '<code>scheduledStartTime</code>' attribute. */ client::DateTime get_scheduled_start_time() const { const Json::Value& storage = Storage("scheduledStartTime"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>scheduledStartTime</code>' attribute. * * The date and time that the broadcast is scheduled to start. The value is * specified in ISO 8601 (YYYY-MM-DDThh:mm:ss.sZ) format. * * @param[in] value The new value. */ void set_scheduled_start_time(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("scheduledStartTime")); } /** * Determine if the '<code>thumbnails</code>' attribute was set. * * @return true if the '<code>thumbnails</code>' attribute was set. */ bool has_thumbnails() const { return Storage().isMember("thumbnails"); } /** * Clears the '<code>thumbnails</code>' attribute. */ void clear_thumbnails() { MutableStorage()->removeMember("thumbnails"); } /** * Get a reference to the value of the '<code>thumbnails</code>' attribute. */ const ThumbnailDetails get_thumbnails() const; /** * Gets a reference to a mutable value of the '<code>thumbnails</code>' * property. * * A map of thumbnail images associated with the broadcast. For each nested * object in this object, the key is the name of the thumbnail image, and the * value is an object that contains other information about the thumbnail. * * @return The result can be modified to change the attribute value. */ ThumbnailDetails mutable_thumbnails(); /** * Determine if the '<code>title</code>' attribute was set. * * @return true if the '<code>title</code>' attribute was set. */ bool has_title() const { return Storage().isMember("title"); } /** * Clears the '<code>title</code>' attribute. */ void clear_title() { MutableStorage()->removeMember("title"); } /** * Get the value of the '<code>title</code>' attribute. */ const StringPiece get_title() const { const Json::Value& v = Storage("title"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>title</code>' attribute. * * The broadcast's title. Note that the broadcast represents exactly one * YouTube video. You can set this field by modifying the broadcast resource * or by setting the title field of the corresponding video resource. * * @param[in] value The new value. */ void set_title(const StringPiece& value) { *MutableStorage("title") = value.data(); } private: void operator=(const LiveBroadcastSnippet&); }; // LiveBroadcastSnippet } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_LIVE_BROADCAST_SNIPPET_H_ <file_sep>/service_apis/drive/google/drive_api/drive_service.cc // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // //------------------------------------------------------------------------------ // This code was generated by google-apis-code-generator 1.5.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. //------------------------------------------------------------------------------ #include "google/drive_api/drive_service.h" #include <string> #include "googleapis/base/integral_types.h" #include "googleapis/client/service/client_service.h" #include "googleapis/client/service/media_uploader.h" #include "googleapis/client/service/service_request_pager.h" #include "googleapis/client/util/status.h" #include "google/drive_api/about.h" #include "google/drive_api/app.h" #include "google/drive_api/app_list.h" #include "google/drive_api/change.h" #include "google/drive_api/change_list.h" #include "google/drive_api/channel.h" #include "google/drive_api/child_list.h" #include "google/drive_api/child_reference.h" #include "google/drive_api/comment.h" #include "google/drive_api/comment_list.h" #include "google/drive_api/comment_reply.h" #include "google/drive_api/comment_reply_list.h" #include "google/drive_api/file.h" #include "google/drive_api/file_list.h" #include "google/drive_api/generated_ids.h" #include "google/drive_api/parent_list.h" #include "google/drive_api/parent_reference.h" #include "google/drive_api/permission.h" #include "google/drive_api/permission_id.h" #include "google/drive_api/permission_list.h" #include "google/drive_api/property.h" #include "google/drive_api/property_list.h" #include "google/drive_api/revision.h" #include "google/drive_api/revision_list.h" #include "google/drive_api/start_page_token.h" #include "google/drive_api/team_drive.h" #include "google/drive_api/team_drive_list.h" #include "googleapis/client/data/data_reader.h" #include "googleapis/client/transport/http_request.h" #include "googleapis/client/transport/http_transport.h" #include "googleapis/client/util/uri_utils.h" #include "googleapis/strings/strcat.h" namespace google_drive_api { using namespace googleapis; const char DriveService::googleapis_API_NAME[] = {"drive"}; const char DriveService::googleapis_API_VERSION[] = {"v2"}; const char DriveService::googleapis_API_GENERATOR[] = { "google-apis-code-generator 1.5.1 / 0.1.4"}; const char DriveService::SCOPES::DRIVE[] = {"https://www.googleapis.com/auth/drive"}; const char DriveService::SCOPES::DRIVE_APPDATA[] = {"https://www.googleapis.com/auth/drive.appdata"}; const char DriveService::SCOPES::DRIVE_APPS_READONLY[] = {"https://www.googleapis.com/auth/drive.apps.readonly"}; const char DriveService::SCOPES::DRIVE_FILE[] = {"https://www.googleapis.com/auth/drive.file"}; const char DriveService::SCOPES::DRIVE_METADATA[] = {"https://www.googleapis.com/auth/drive.metadata"}; const char DriveService::SCOPES::DRIVE_METADATA_READONLY[] = {"https://www.googleapis.com/auth/drive.metadata.readonly"}; const char DriveService::SCOPES::DRIVE_PHOTOS_READONLY[] = {"https://www.googleapis.com/auth/drive.photos.readonly"}; const char DriveService::SCOPES::DRIVE_READONLY[] = {"https://www.googleapis.com/auth/drive.readonly"}; const char DriveService::SCOPES::DRIVE_SCRIPTS[] = {"https://www.googleapis.com/auth/drive.scripts"}; DriveServiceBaseRequest::DriveServiceBaseRequest( const client::ClientService* service, client::AuthorizationCredential* credential, client::HttpRequest::HttpMethod method, const StringPiece& uri_template) : client::ClientServiceRequest( service, credential, method, uri_template), alt_("json"), pretty_print_(true), _have_alt_(false), _have_fields_(false), _have_key_(false), _have_oauth_token_(false), _have_pretty_print_(false), _have_quota_user_(false), _have_user_ip_(false) { } DriveServiceBaseRequest::~DriveServiceBaseRequest() { } util::Status DriveServiceBaseRequest::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return client::StatusInvalidArgument( StrCat("Unknown url variable='", variable_name, "'")); } util::Status DriveServiceBaseRequest::AppendOptionalQueryParameters( string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_alt_) { StrAppend(target, sep, "alt=", client::CppValueToEscapedUrlValue( alt_)); sep = "&"; } if (_have_fields_) { StrAppend(target, sep, "fields=", client::CppValueToEscapedUrlValue( fields_)); sep = "&"; } if (_have_key_) { StrAppend(target, sep, "key=", client::CppValueToEscapedUrlValue( key_)); sep = "&"; } if (_have_oauth_token_) { StrAppend(target, sep, "oauth_token=", client::CppValueToEscapedUrlValue( oauth_token_)); sep = "&"; } if (_have_pretty_print_) { StrAppend(target, sep, "prettyPrint=", client::CppValueToEscapedUrlValue( pretty_print_)); sep = "&"; } if (_have_quota_user_) { StrAppend(target, sep, "quotaUser=", client::CppValueToEscapedUrlValue( quota_user_)); sep = "&"; } if (_have_user_ip_) { StrAppend(target, sep, "userIp=", client::CppValueToEscapedUrlValue( user_ip_)); sep = "&"; } return client::ClientServiceRequest ::AppendOptionalQueryParameters(target); } void DriveServiceBaseRequest::AddJsonContentToRequest( const client::JsonCppData *content) { client::HttpRequest* _http_request_ = mutable_http_request(); _http_request_->set_content_type( client::HttpRequest::ContentType_JSON); _http_request_->set_content_reader(content->MakeJsonReader()); } // Standard constructor. AboutResource_GetMethod::AboutResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "about"), include_subscribed_(true), max_change_id_count_(1), _have_include_subscribed_(false), _have_max_change_id_count_(false), _have_start_change_id_(false) { } // Standard destructor. AboutResource_GetMethod::~AboutResource_GetMethod() { } util::Status AboutResource_GetMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_include_subscribed_) { StrAppend(target, sep, "includeSubscribed=", client::CppValueToEscapedUrlValue( include_subscribed_)); sep = "&"; } if (_have_max_change_id_count_) { StrAppend(target, sep, "maxChangeIdCount=", client::CppValueToEscapedUrlValue( max_change_id_count_)); sep = "&"; } if (_have_start_change_id_) { StrAppend(target, sep, "startChangeId=", client::CppValueToEscapedUrlValue( start_change_id_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status AboutResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. AppsResource_GetMethod::AppsResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& app_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "apps/{appId}"), app_id_(app_id.as_string()) { } // Standard destructor. AppsResource_GetMethod::~AppsResource_GetMethod() { } util::Status AppsResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "appId") { client::UriTemplate::AppendValue( app_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. AppsResource_ListMethod::AppsResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "apps"), _have_app_filter_extensions_(false), _have_app_filter_mime_types_(false), _have_language_code_(false) { } // Standard destructor. AppsResource_ListMethod::~AppsResource_ListMethod() { } util::Status AppsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_app_filter_extensions_) { StrAppend(target, sep, "appFilterExtensions=", client::CppValueToEscapedUrlValue( app_filter_extensions_)); sep = "&"; } if (_have_app_filter_mime_types_) { StrAppend(target, sep, "appFilterMimeTypes=", client::CppValueToEscapedUrlValue( app_filter_mime_types_)); sep = "&"; } if (_have_language_code_) { StrAppend(target, sep, "languageCode=", client::CppValueToEscapedUrlValue( language_code_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status AppsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ChangesResource_GetMethod::ChangesResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& change_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "changes/{changeId}"), change_id_(change_id.as_string()), supports_team_drives_(false), _have_supports_team_drives_(false), _have_team_drive_id_(false) { } // Standard destructor. ChangesResource_GetMethod::~ChangesResource_GetMethod() { } util::Status ChangesResource_GetMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } if (_have_team_drive_id_) { StrAppend(target, sep, "teamDriveId=", client::CppValueToEscapedUrlValue( team_drive_id_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ChangesResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "changeId") { client::UriTemplate::AppendValue( change_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ChangesResource_GetStartPageTokenMethod::ChangesResource_GetStartPageTokenMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "changes/startPageToken"), supports_team_drives_(false), _have_supports_team_drives_(false), _have_team_drive_id_(false) { } // Standard destructor. ChangesResource_GetStartPageTokenMethod::~ChangesResource_GetStartPageTokenMethod() { } util::Status ChangesResource_GetStartPageTokenMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } if (_have_team_drive_id_) { StrAppend(target, sep, "teamDriveId=", client::CppValueToEscapedUrlValue( team_drive_id_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ChangesResource_GetStartPageTokenMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ChangesResource_ListMethod::ChangesResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "changes"), include_corpus_removals_(false), include_deleted_(true), include_subscribed_(true), include_team_drive_items_(false), max_results_(100), supports_team_drives_(false), _have_include_corpus_removals_(false), _have_include_deleted_(false), _have_include_subscribed_(false), _have_include_team_drive_items_(false), _have_max_results_(false), _have_page_token_(false), _have_spaces_(false), _have_start_change_id_(false), _have_supports_team_drives_(false), _have_team_drive_id_(false) { } // Standard destructor. ChangesResource_ListMethod::~ChangesResource_ListMethod() { } util::Status ChangesResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_include_corpus_removals_) { StrAppend(target, sep, "includeCorpusRemovals=", client::CppValueToEscapedUrlValue( include_corpus_removals_)); sep = "&"; } if (_have_include_deleted_) { StrAppend(target, sep, "includeDeleted=", client::CppValueToEscapedUrlValue( include_deleted_)); sep = "&"; } if (_have_include_subscribed_) { StrAppend(target, sep, "includeSubscribed=", client::CppValueToEscapedUrlValue( include_subscribed_)); sep = "&"; } if (_have_include_team_drive_items_) { StrAppend(target, sep, "includeTeamDriveItems=", client::CppValueToEscapedUrlValue( include_team_drive_items_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_spaces_) { StrAppend(target, sep, "spaces=", client::CppValueToEscapedUrlValue( spaces_)); sep = "&"; } if (_have_start_change_id_) { StrAppend(target, sep, "startChangeId=", client::CppValueToEscapedUrlValue( start_change_id_)); sep = "&"; } if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } if (_have_team_drive_id_) { StrAppend(target, sep, "teamDriveId=", client::CppValueToEscapedUrlValue( team_drive_id_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ChangesResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ChangesResource_WatchMethod::ChangesResource_WatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const Channel& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "changes/watch"), include_corpus_removals_(false), include_deleted_(true), include_subscribed_(true), include_team_drive_items_(false), max_results_(100), supports_team_drives_(false), _have_include_corpus_removals_(false), _have_include_deleted_(false), _have_include_subscribed_(false), _have_include_team_drive_items_(false), _have_max_results_(false), _have_page_token_(false), _have_spaces_(false), _have_start_change_id_(false), _have_supports_team_drives_(false), _have_team_drive_id_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. ChangesResource_WatchMethod::~ChangesResource_WatchMethod() { } util::Status ChangesResource_WatchMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_include_corpus_removals_) { StrAppend(target, sep, "includeCorpusRemovals=", client::CppValueToEscapedUrlValue( include_corpus_removals_)); sep = "&"; } if (_have_include_deleted_) { StrAppend(target, sep, "includeDeleted=", client::CppValueToEscapedUrlValue( include_deleted_)); sep = "&"; } if (_have_include_subscribed_) { StrAppend(target, sep, "includeSubscribed=", client::CppValueToEscapedUrlValue( include_subscribed_)); sep = "&"; } if (_have_include_team_drive_items_) { StrAppend(target, sep, "includeTeamDriveItems=", client::CppValueToEscapedUrlValue( include_team_drive_items_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_spaces_) { StrAppend(target, sep, "spaces=", client::CppValueToEscapedUrlValue( spaces_)); sep = "&"; } if (_have_start_change_id_) { StrAppend(target, sep, "startChangeId=", client::CppValueToEscapedUrlValue( start_change_id_)); sep = "&"; } if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } if (_have_team_drive_id_) { StrAppend(target, sep, "teamDriveId=", client::CppValueToEscapedUrlValue( team_drive_id_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ChangesResource_WatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ChannelsResource_StopMethod::ChannelsResource_StopMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const Channel& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "channels/stop") { AddJsonContentToRequest(&__request_content__); } // Standard destructor. ChannelsResource_StopMethod::~ChannelsResource_StopMethod() { } // Standard constructor. ChildrenResource_DeleteMethod::ChildrenResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& folder_id, const StringPiece& child_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "files/{folderId}/children/{childId}"), folder_id_(folder_id.as_string()), child_id_(child_id.as_string()) { } // Standard destructor. ChildrenResource_DeleteMethod::~ChildrenResource_DeleteMethod() { } util::Status ChildrenResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "folderId") { client::UriTemplate::AppendValue( folder_id_, config, target); return client::StatusOk(); } if (variable_name == "childId") { client::UriTemplate::AppendValue( child_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ChildrenResource_GetMethod::ChildrenResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& folder_id, const StringPiece& child_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{folderId}/children/{childId}"), folder_id_(folder_id.as_string()), child_id_(child_id.as_string()) { } // Standard destructor. ChildrenResource_GetMethod::~ChildrenResource_GetMethod() { } util::Status ChildrenResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "folderId") { client::UriTemplate::AppendValue( folder_id_, config, target); return client::StatusOk(); } if (variable_name == "childId") { client::UriTemplate::AppendValue( child_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ChildrenResource_InsertMethod::ChildrenResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& folder_id, const ChildReference& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "files/{folderId}/children"), folder_id_(folder_id.as_string()), supports_team_drives_(false), _have_supports_team_drives_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. ChildrenResource_InsertMethod::~ChildrenResource_InsertMethod() { } util::Status ChildrenResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ChildrenResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "folderId") { client::UriTemplate::AppendValue( folder_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ChildrenResource_ListMethod::ChildrenResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& folder_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{folderId}/children"), folder_id_(folder_id.as_string()), max_results_(100), _have_max_results_(false), _have_order_by_(false), _have_page_token_(false), _have_q_(false) { } // Standard destructor. ChildrenResource_ListMethod::~ChildrenResource_ListMethod() { } util::Status ChildrenResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_order_by_) { StrAppend(target, sep, "orderBy=", client::CppValueToEscapedUrlValue( order_by_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_q_) { StrAppend(target, sep, "q=", client::CppValueToEscapedUrlValue( q_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ChildrenResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "folderId") { client::UriTemplate::AppendValue( folder_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CommentsResource_DeleteMethod::CommentsResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "files/{fileId}/comments/{commentId}"), file_id_(file_id.as_string()), comment_id_(comment_id.as_string()) { } // Standard destructor. CommentsResource_DeleteMethod::~CommentsResource_DeleteMethod() { } util::Status CommentsResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "commentId") { client::UriTemplate::AppendValue( comment_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CommentsResource_GetMethod::CommentsResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{fileId}/comments/{commentId}"), file_id_(file_id.as_string()), comment_id_(comment_id.as_string()), include_deleted_(false), _have_include_deleted_(false) { } // Standard destructor. CommentsResource_GetMethod::~CommentsResource_GetMethod() { } util::Status CommentsResource_GetMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_include_deleted_) { StrAppend(target, sep, "includeDeleted=", client::CppValueToEscapedUrlValue( include_deleted_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CommentsResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "commentId") { client::UriTemplate::AppendValue( comment_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CommentsResource_InsertMethod::CommentsResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Comment& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "files/{fileId}/comments"), file_id_(file_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. CommentsResource_InsertMethod::~CommentsResource_InsertMethod() { } util::Status CommentsResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CommentsResource_ListMethod::CommentsResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{fileId}/comments"), file_id_(file_id.as_string()), include_deleted_(false), max_results_(20), _have_include_deleted_(false), _have_max_results_(false), _have_page_token_(false), _have_updated_min_(false) { } // Standard destructor. CommentsResource_ListMethod::~CommentsResource_ListMethod() { } util::Status CommentsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_include_deleted_) { StrAppend(target, sep, "includeDeleted=", client::CppValueToEscapedUrlValue( include_deleted_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_updated_min_) { StrAppend(target, sep, "updatedMin=", client::CppValueToEscapedUrlValue( updated_min_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status CommentsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CommentsResource_PatchMethod::CommentsResource_PatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const Comment& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::PATCH, "files/{fileId}/comments/{commentId}"), file_id_(file_id.as_string()), comment_id_(comment_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. CommentsResource_PatchMethod::~CommentsResource_PatchMethod() { } util::Status CommentsResource_PatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "commentId") { client::UriTemplate::AppendValue( comment_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. CommentsResource_UpdateMethod::CommentsResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const Comment& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "files/{fileId}/comments/{commentId}"), file_id_(file_id.as_string()), comment_id_(comment_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. CommentsResource_UpdateMethod::~CommentsResource_UpdateMethod() { } util::Status CommentsResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "commentId") { client::UriTemplate::AppendValue( comment_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. FilesResource_CopyMethod::FilesResource_CopyMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const File& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "files/{fileId}/copy"), file_id_(file_id.as_string()), convert_(false), ocr_(false), pinned_(false), supports_team_drives_(false), visibility_("DEFAULT"), _have_convert_(false), _have_ocr_(false), _have_ocr_language_(false), _have_pinned_(false), _have_supports_team_drives_(false), _have_timed_text_language_(false), _have_timed_text_track_name_(false), _have_visibility_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. FilesResource_CopyMethod::~FilesResource_CopyMethod() { } util::Status FilesResource_CopyMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_convert_) { StrAppend(target, sep, "convert=", client::CppValueToEscapedUrlValue( convert_)); sep = "&"; } if (_have_ocr_) { StrAppend(target, sep, "ocr=", client::CppValueToEscapedUrlValue( ocr_)); sep = "&"; } if (_have_ocr_language_) { StrAppend(target, sep, "ocrLanguage=", client::CppValueToEscapedUrlValue( ocr_language_)); sep = "&"; } if (_have_pinned_) { StrAppend(target, sep, "pinned=", client::CppValueToEscapedUrlValue( pinned_)); sep = "&"; } if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } if (_have_timed_text_language_) { StrAppend(target, sep, "timedTextLanguage=", client::CppValueToEscapedUrlValue( timed_text_language_)); sep = "&"; } if (_have_timed_text_track_name_) { StrAppend(target, sep, "timedTextTrackName=", client::CppValueToEscapedUrlValue( timed_text_track_name_)); sep = "&"; } if (_have_visibility_) { StrAppend(target, sep, "visibility=", client::CppValueToEscapedUrlValue( visibility_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status FilesResource_CopyMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. FilesResource_DeleteMethod::FilesResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "files/{fileId}"), file_id_(file_id.as_string()), supports_team_drives_(false), _have_supports_team_drives_(false) { } // Standard destructor. FilesResource_DeleteMethod::~FilesResource_DeleteMethod() { } util::Status FilesResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status FilesResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. FilesResource_EmptyTrashMethod::FilesResource_EmptyTrashMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "files/trash") { } // Standard destructor. FilesResource_EmptyTrashMethod::~FilesResource_EmptyTrashMethod() { } // Standard constructor. FilesResource_ExportMethod::FilesResource_ExportMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& mime_type) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{fileId}/export"), file_id_(file_id.as_string()), mime_type_(mime_type.as_string()) { } // Standard destructor. FilesResource_ExportMethod::~FilesResource_ExportMethod() { } util::Status FilesResource_ExportMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "mimeType=", client::CppValueToEscapedUrlValue( mime_type_)); sep = "&"; return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status FilesResource_ExportMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. FilesResource_GenerateIdsMethod::FilesResource_GenerateIdsMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/generateIds"), max_results_(10), space_("drive"), _have_max_results_(false), _have_space_(false) { } // Standard destructor. FilesResource_GenerateIdsMethod::~FilesResource_GenerateIdsMethod() { } util::Status FilesResource_GenerateIdsMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_space_) { StrAppend(target, sep, "space=", client::CppValueToEscapedUrlValue( space_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status FilesResource_GenerateIdsMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. FilesResource_GetMethod::FilesResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{fileId}"), file_id_(file_id.as_string()), acknowledge_abuse_(false), supports_team_drives_(false), update_viewed_date_(false), _have_acknowledge_abuse_(false), _have_projection_(false), _have_revision_id_(false), _have_supports_team_drives_(false), _have_update_viewed_date_(false) { } // Standard destructor. FilesResource_GetMethod::~FilesResource_GetMethod() { } util::Status FilesResource_GetMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_acknowledge_abuse_) { StrAppend(target, sep, "acknowledgeAbuse=", client::CppValueToEscapedUrlValue( acknowledge_abuse_)); sep = "&"; } if (_have_projection_) { StrAppend(target, sep, "projection=", client::CppValueToEscapedUrlValue( projection_)); sep = "&"; } if (_have_revision_id_) { StrAppend(target, sep, "revisionId=", client::CppValueToEscapedUrlValue( revision_id_)); sep = "&"; } if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } if (_have_update_viewed_date_) { StrAppend(target, sep, "updateViewedDate=", client::CppValueToEscapedUrlValue( update_viewed_date_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status FilesResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // static const client::MediaUploadSpec FilesResource_InsertMethod::SIMPLE_MEDIA_UPLOAD( "simple", "/upload/drive/v2/files", true); // static const client::MediaUploadSpec FilesResource_InsertMethod::RESUMABLE_MEDIA_UPLOAD( "resumable", "/resumable/upload/drive/v2/files", true); // Deprecated constructor did not take media upload arguments. FilesResource_InsertMethod::FilesResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "files"), convert_(false), ocr_(false), pinned_(false), supports_team_drives_(false), use_content_as_indexable_text_(false), visibility_("DEFAULT"), _have_convert_(false), _have_ocr_(false), _have_ocr_language_(false), _have_pinned_(false), _have_supports_team_drives_(false), _have_timed_text_language_(false), _have_timed_text_track_name_(false), _have_use_content_as_indexable_text_(false), _have_visibility_(false) { uploader_.reset(new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "files"))); } // Standard constructor. FilesResource_InsertMethod::FilesResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const File* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "files"), convert_(false), ocr_(false), pinned_(false), supports_team_drives_(false), use_content_as_indexable_text_(false), visibility_("DEFAULT"), _have_convert_(false), _have_ocr_(false), _have_ocr_language_(false), _have_pinned_(false), _have_supports_team_drives_(false), _have_timed_text_language_(false), _have_timed_text_track_name_(false), _have_use_content_as_indexable_text_(false), _have_visibility_(false) { if (_media_content_reader_) { client::MediaUploader* uploader = new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "files")); if (_metadata_) { uploader->set_metadata(*_metadata_); } uploader->set_media_content_reader( _media_content_type_.as_string(), _media_content_reader_); ResetMediaUploader(uploader); } else { AddJsonContentToRequest(_metadata_); } } // Standard destructor. FilesResource_InsertMethod::~FilesResource_InsertMethod() { } util::Status FilesResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_convert_) { StrAppend(target, sep, "convert=", client::CppValueToEscapedUrlValue( convert_)); sep = "&"; } if (_have_ocr_) { StrAppend(target, sep, "ocr=", client::CppValueToEscapedUrlValue( ocr_)); sep = "&"; } if (_have_ocr_language_) { StrAppend(target, sep, "ocrLanguage=", client::CppValueToEscapedUrlValue( ocr_language_)); sep = "&"; } if (_have_pinned_) { StrAppend(target, sep, "pinned=", client::CppValueToEscapedUrlValue( pinned_)); sep = "&"; } if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } if (_have_timed_text_language_) { StrAppend(target, sep, "timedTextLanguage=", client::CppValueToEscapedUrlValue( timed_text_language_)); sep = "&"; } if (_have_timed_text_track_name_) { StrAppend(target, sep, "timedTextTrackName=", client::CppValueToEscapedUrlValue( timed_text_track_name_)); sep = "&"; } if (_have_use_content_as_indexable_text_) { StrAppend(target, sep, "useContentAsIndexableText=", client::CppValueToEscapedUrlValue( use_content_as_indexable_text_)); sep = "&"; } if (_have_visibility_) { StrAppend(target, sep, "visibility=", client::CppValueToEscapedUrlValue( visibility_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status FilesResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. FilesResource_ListMethod::FilesResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files"), include_team_drive_items_(false), max_results_(100), supports_team_drives_(false), _have_corpora_(false), _have_corpus_(false), _have_include_team_drive_items_(false), _have_max_results_(false), _have_order_by_(false), _have_page_token_(false), _have_projection_(false), _have_q_(false), _have_spaces_(false), _have_supports_team_drives_(false), _have_team_drive_id_(false) { } // Standard destructor. FilesResource_ListMethod::~FilesResource_ListMethod() { } util::Status FilesResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_corpora_) { StrAppend(target, sep, "corpora=", client::CppValueToEscapedUrlValue( corpora_)); sep = "&"; } if (_have_corpus_) { StrAppend(target, sep, "corpus=", client::CppValueToEscapedUrlValue( corpus_)); sep = "&"; } if (_have_include_team_drive_items_) { StrAppend(target, sep, "includeTeamDriveItems=", client::CppValueToEscapedUrlValue( include_team_drive_items_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_order_by_) { StrAppend(target, sep, "orderBy=", client::CppValueToEscapedUrlValue( order_by_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_projection_) { StrAppend(target, sep, "projection=", client::CppValueToEscapedUrlValue( projection_)); sep = "&"; } if (_have_q_) { StrAppend(target, sep, "q=", client::CppValueToEscapedUrlValue( q_)); sep = "&"; } if (_have_spaces_) { StrAppend(target, sep, "spaces=", client::CppValueToEscapedUrlValue( spaces_)); sep = "&"; } if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } if (_have_team_drive_id_) { StrAppend(target, sep, "teamDriveId=", client::CppValueToEscapedUrlValue( team_drive_id_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status FilesResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. FilesResource_PatchMethod::FilesResource_PatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const File& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::PATCH, "files/{fileId}"), file_id_(file_id.as_string()), convert_(false), new_revision_(true), ocr_(false), pinned_(false), set_modified_date_(false), supports_team_drives_(false), update_viewed_date_(true), use_content_as_indexable_text_(false), _have_add_parents_(false), _have_convert_(false), _have_modified_date_behavior_(false), _have_new_revision_(false), _have_ocr_(false), _have_ocr_language_(false), _have_pinned_(false), _have_remove_parents_(false), _have_set_modified_date_(false), _have_supports_team_drives_(false), _have_timed_text_language_(false), _have_timed_text_track_name_(false), _have_update_viewed_date_(false), _have_use_content_as_indexable_text_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. FilesResource_PatchMethod::~FilesResource_PatchMethod() { } util::Status FilesResource_PatchMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_add_parents_) { StrAppend(target, sep, "addParents=", client::CppValueToEscapedUrlValue( add_parents_)); sep = "&"; } if (_have_convert_) { StrAppend(target, sep, "convert=", client::CppValueToEscapedUrlValue( convert_)); sep = "&"; } if (_have_modified_date_behavior_) { StrAppend(target, sep, "modifiedDateBehavior=", client::CppValueToEscapedUrlValue( modified_date_behavior_)); sep = "&"; } if (_have_new_revision_) { StrAppend(target, sep, "newRevision=", client::CppValueToEscapedUrlValue( new_revision_)); sep = "&"; } if (_have_ocr_) { StrAppend(target, sep, "ocr=", client::CppValueToEscapedUrlValue( ocr_)); sep = "&"; } if (_have_ocr_language_) { StrAppend(target, sep, "ocrLanguage=", client::CppValueToEscapedUrlValue( ocr_language_)); sep = "&"; } if (_have_pinned_) { StrAppend(target, sep, "pinned=", client::CppValueToEscapedUrlValue( pinned_)); sep = "&"; } if (_have_remove_parents_) { StrAppend(target, sep, "removeParents=", client::CppValueToEscapedUrlValue( remove_parents_)); sep = "&"; } if (_have_set_modified_date_) { StrAppend(target, sep, "setModifiedDate=", client::CppValueToEscapedUrlValue( set_modified_date_)); sep = "&"; } if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } if (_have_timed_text_language_) { StrAppend(target, sep, "timedTextLanguage=", client::CppValueToEscapedUrlValue( timed_text_language_)); sep = "&"; } if (_have_timed_text_track_name_) { StrAppend(target, sep, "timedTextTrackName=", client::CppValueToEscapedUrlValue( timed_text_track_name_)); sep = "&"; } if (_have_update_viewed_date_) { StrAppend(target, sep, "updateViewedDate=", client::CppValueToEscapedUrlValue( update_viewed_date_)); sep = "&"; } if (_have_use_content_as_indexable_text_) { StrAppend(target, sep, "useContentAsIndexableText=", client::CppValueToEscapedUrlValue( use_content_as_indexable_text_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status FilesResource_PatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. FilesResource_TouchMethod::FilesResource_TouchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "files/{fileId}/touch"), file_id_(file_id.as_string()), supports_team_drives_(false), _have_supports_team_drives_(false) { } // Standard destructor. FilesResource_TouchMethod::~FilesResource_TouchMethod() { } util::Status FilesResource_TouchMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status FilesResource_TouchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. FilesResource_TrashMethod::FilesResource_TrashMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "files/{fileId}/trash"), file_id_(file_id.as_string()), supports_team_drives_(false), _have_supports_team_drives_(false) { } // Standard destructor. FilesResource_TrashMethod::~FilesResource_TrashMethod() { } util::Status FilesResource_TrashMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status FilesResource_TrashMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. FilesResource_UntrashMethod::FilesResource_UntrashMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "files/{fileId}/untrash"), file_id_(file_id.as_string()), supports_team_drives_(false), _have_supports_team_drives_(false) { } // Standard destructor. FilesResource_UntrashMethod::~FilesResource_UntrashMethod() { } util::Status FilesResource_UntrashMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status FilesResource_UntrashMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // static const client::MediaUploadSpec FilesResource_UpdateMethod::SIMPLE_MEDIA_UPLOAD( "simple", "/upload/drive/v2/files/{fileId}", true); // static const client::MediaUploadSpec FilesResource_UpdateMethod::RESUMABLE_MEDIA_UPLOAD( "resumable", "/resumable/upload/drive/v2/files/{fileId}", true); // Deprecated constructor did not take media upload arguments. FilesResource_UpdateMethod::FilesResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "files/{fileId}"), file_id_(file_id.as_string()), convert_(false), new_revision_(true), ocr_(false), pinned_(false), set_modified_date_(false), supports_team_drives_(false), update_viewed_date_(true), use_content_as_indexable_text_(false), _have_add_parents_(false), _have_convert_(false), _have_modified_date_behavior_(false), _have_new_revision_(false), _have_ocr_(false), _have_ocr_language_(false), _have_pinned_(false), _have_remove_parents_(false), _have_set_modified_date_(false), _have_supports_team_drives_(false), _have_timed_text_language_(false), _have_timed_text_track_name_(false), _have_update_viewed_date_(false), _have_use_content_as_indexable_text_(false) { uploader_.reset(new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "files/{fileId}"))); } // Standard constructor. FilesResource_UpdateMethod::FilesResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const File* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "files/{fileId}"), file_id_(file_id.as_string()), convert_(false), new_revision_(true), ocr_(false), pinned_(false), set_modified_date_(false), supports_team_drives_(false), update_viewed_date_(true), use_content_as_indexable_text_(false), _have_add_parents_(false), _have_convert_(false), _have_modified_date_behavior_(false), _have_new_revision_(false), _have_ocr_(false), _have_ocr_language_(false), _have_pinned_(false), _have_remove_parents_(false), _have_set_modified_date_(false), _have_supports_team_drives_(false), _have_timed_text_language_(false), _have_timed_text_track_name_(false), _have_update_viewed_date_(false), _have_use_content_as_indexable_text_(false) { if (_media_content_reader_) { client::MediaUploader* uploader = new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "files/{fileId}")); if (_metadata_) { uploader->set_metadata(*_metadata_); } uploader->set_media_content_reader( _media_content_type_.as_string(), _media_content_reader_); ResetMediaUploader(uploader); } else { AddJsonContentToRequest(_metadata_); } } // Standard destructor. FilesResource_UpdateMethod::~FilesResource_UpdateMethod() { } util::Status FilesResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_add_parents_) { StrAppend(target, sep, "addParents=", client::CppValueToEscapedUrlValue( add_parents_)); sep = "&"; } if (_have_convert_) { StrAppend(target, sep, "convert=", client::CppValueToEscapedUrlValue( convert_)); sep = "&"; } if (_have_modified_date_behavior_) { StrAppend(target, sep, "modifiedDateBehavior=", client::CppValueToEscapedUrlValue( modified_date_behavior_)); sep = "&"; } if (_have_new_revision_) { StrAppend(target, sep, "newRevision=", client::CppValueToEscapedUrlValue( new_revision_)); sep = "&"; } if (_have_ocr_) { StrAppend(target, sep, "ocr=", client::CppValueToEscapedUrlValue( ocr_)); sep = "&"; } if (_have_ocr_language_) { StrAppend(target, sep, "ocrLanguage=", client::CppValueToEscapedUrlValue( ocr_language_)); sep = "&"; } if (_have_pinned_) { StrAppend(target, sep, "pinned=", client::CppValueToEscapedUrlValue( pinned_)); sep = "&"; } if (_have_remove_parents_) { StrAppend(target, sep, "removeParents=", client::CppValueToEscapedUrlValue( remove_parents_)); sep = "&"; } if (_have_set_modified_date_) { StrAppend(target, sep, "setModifiedDate=", client::CppValueToEscapedUrlValue( set_modified_date_)); sep = "&"; } if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } if (_have_timed_text_language_) { StrAppend(target, sep, "timedTextLanguage=", client::CppValueToEscapedUrlValue( timed_text_language_)); sep = "&"; } if (_have_timed_text_track_name_) { StrAppend(target, sep, "timedTextTrackName=", client::CppValueToEscapedUrlValue( timed_text_track_name_)); sep = "&"; } if (_have_update_viewed_date_) { StrAppend(target, sep, "updateViewedDate=", client::CppValueToEscapedUrlValue( update_viewed_date_)); sep = "&"; } if (_have_use_content_as_indexable_text_) { StrAppend(target, sep, "useContentAsIndexableText=", client::CppValueToEscapedUrlValue( use_content_as_indexable_text_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status FilesResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. FilesResource_WatchMethod::FilesResource_WatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Channel& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "files/{fileId}/watch"), file_id_(file_id.as_string()), acknowledge_abuse_(false), supports_team_drives_(false), update_viewed_date_(false), _have_acknowledge_abuse_(false), _have_projection_(false), _have_revision_id_(false), _have_supports_team_drives_(false), _have_update_viewed_date_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. FilesResource_WatchMethod::~FilesResource_WatchMethod() { } util::Status FilesResource_WatchMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_acknowledge_abuse_) { StrAppend(target, sep, "acknowledgeAbuse=", client::CppValueToEscapedUrlValue( acknowledge_abuse_)); sep = "&"; } if (_have_projection_) { StrAppend(target, sep, "projection=", client::CppValueToEscapedUrlValue( projection_)); sep = "&"; } if (_have_revision_id_) { StrAppend(target, sep, "revisionId=", client::CppValueToEscapedUrlValue( revision_id_)); sep = "&"; } if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } if (_have_update_viewed_date_) { StrAppend(target, sep, "updateViewedDate=", client::CppValueToEscapedUrlValue( update_viewed_date_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status FilesResource_WatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ParentsResource_DeleteMethod::ParentsResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& parent_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "files/{fileId}/parents/{parentId}"), file_id_(file_id.as_string()), parent_id_(parent_id.as_string()) { } // Standard destructor. ParentsResource_DeleteMethod::~ParentsResource_DeleteMethod() { } util::Status ParentsResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "parentId") { client::UriTemplate::AppendValue( parent_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ParentsResource_GetMethod::ParentsResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& parent_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{fileId}/parents/{parentId}"), file_id_(file_id.as_string()), parent_id_(parent_id.as_string()) { } // Standard destructor. ParentsResource_GetMethod::~ParentsResource_GetMethod() { } util::Status ParentsResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "parentId") { client::UriTemplate::AppendValue( parent_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ParentsResource_InsertMethod::ParentsResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const ParentReference& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "files/{fileId}/parents"), file_id_(file_id.as_string()), supports_team_drives_(false), _have_supports_team_drives_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. ParentsResource_InsertMethod::~ParentsResource_InsertMethod() { } util::Status ParentsResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status ParentsResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. ParentsResource_ListMethod::ParentsResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{fileId}/parents"), file_id_(file_id.as_string()) { } // Standard destructor. ParentsResource_ListMethod::~ParentsResource_ListMethod() { } util::Status ParentsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PermissionsResource_DeleteMethod::PermissionsResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "files/{fileId}/permissions/{permissionId}"), file_id_(file_id.as_string()), permission_id_(permission_id.as_string()), supports_team_drives_(false), _have_supports_team_drives_(false) { } // Standard destructor. PermissionsResource_DeleteMethod::~PermissionsResource_DeleteMethod() { } util::Status PermissionsResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PermissionsResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "permissionId") { client::UriTemplate::AppendValue( permission_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PermissionsResource_GetMethod::PermissionsResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{fileId}/permissions/{permissionId}"), file_id_(file_id.as_string()), permission_id_(permission_id.as_string()), supports_team_drives_(false), _have_supports_team_drives_(false) { } // Standard destructor. PermissionsResource_GetMethod::~PermissionsResource_GetMethod() { } util::Status PermissionsResource_GetMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PermissionsResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "permissionId") { client::UriTemplate::AppendValue( permission_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PermissionsResource_GetIdForEmailMethod::PermissionsResource_GetIdForEmailMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& email) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "permissionIds/{email}"), email_(email.as_string()) { } // Standard destructor. PermissionsResource_GetIdForEmailMethod::~PermissionsResource_GetIdForEmailMethod() { } util::Status PermissionsResource_GetIdForEmailMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "email") { client::UriTemplate::AppendValue( email_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PermissionsResource_InsertMethod::PermissionsResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Permission& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "files/{fileId}/permissions"), file_id_(file_id.as_string()), send_notification_emails_(true), supports_team_drives_(false), _have_email_message_(false), _have_send_notification_emails_(false), _have_supports_team_drives_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. PermissionsResource_InsertMethod::~PermissionsResource_InsertMethod() { } util::Status PermissionsResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_email_message_) { StrAppend(target, sep, "emailMessage=", client::CppValueToEscapedUrlValue( email_message_)); sep = "&"; } if (_have_send_notification_emails_) { StrAppend(target, sep, "sendNotificationEmails=", client::CppValueToEscapedUrlValue( send_notification_emails_)); sep = "&"; } if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PermissionsResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PermissionsResource_ListMethod::PermissionsResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{fileId}/permissions"), file_id_(file_id.as_string()), supports_team_drives_(false), _have_max_results_(false), _have_page_token_(false), _have_supports_team_drives_(false) { } // Standard destructor. PermissionsResource_ListMethod::~PermissionsResource_ListMethod() { } util::Status PermissionsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PermissionsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PermissionsResource_PatchMethod::PermissionsResource_PatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id, const Permission& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::PATCH, "files/{fileId}/permissions/{permissionId}"), file_id_(file_id.as_string()), permission_id_(permission_id.as_string()), remove_expiration_(false), supports_team_drives_(false), transfer_ownership_(false), _have_remove_expiration_(false), _have_supports_team_drives_(false), _have_transfer_ownership_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. PermissionsResource_PatchMethod::~PermissionsResource_PatchMethod() { } util::Status PermissionsResource_PatchMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_remove_expiration_) { StrAppend(target, sep, "removeExpiration=", client::CppValueToEscapedUrlValue( remove_expiration_)); sep = "&"; } if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } if (_have_transfer_ownership_) { StrAppend(target, sep, "transferOwnership=", client::CppValueToEscapedUrlValue( transfer_ownership_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PermissionsResource_PatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "permissionId") { client::UriTemplate::AppendValue( permission_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PermissionsResource_UpdateMethod::PermissionsResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id, const Permission& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "files/{fileId}/permissions/{permissionId}"), file_id_(file_id.as_string()), permission_id_(permission_id.as_string()), remove_expiration_(false), supports_team_drives_(false), transfer_ownership_(false), _have_remove_expiration_(false), _have_supports_team_drives_(false), _have_transfer_ownership_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. PermissionsResource_UpdateMethod::~PermissionsResource_UpdateMethod() { } util::Status PermissionsResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_remove_expiration_) { StrAppend(target, sep, "removeExpiration=", client::CppValueToEscapedUrlValue( remove_expiration_)); sep = "&"; } if (_have_supports_team_drives_) { StrAppend(target, sep, "supportsTeamDrives=", client::CppValueToEscapedUrlValue( supports_team_drives_)); sep = "&"; } if (_have_transfer_ownership_) { StrAppend(target, sep, "transferOwnership=", client::CppValueToEscapedUrlValue( transfer_ownership_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PermissionsResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "permissionId") { client::UriTemplate::AppendValue( permission_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PropertiesResource_DeleteMethod::PropertiesResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "files/{fileId}/properties/{propertyKey}"), file_id_(file_id.as_string()), property_key_(property_key.as_string()), visibility_("private"), _have_visibility_(false) { } // Standard destructor. PropertiesResource_DeleteMethod::~PropertiesResource_DeleteMethod() { } util::Status PropertiesResource_DeleteMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_visibility_) { StrAppend(target, sep, "visibility=", client::CppValueToEscapedUrlValue( visibility_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PropertiesResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "propertyKey") { client::UriTemplate::AppendValue( property_key_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PropertiesResource_GetMethod::PropertiesResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{fileId}/properties/{propertyKey}"), file_id_(file_id.as_string()), property_key_(property_key.as_string()), visibility_("private"), _have_visibility_(false) { } // Standard destructor. PropertiesResource_GetMethod::~PropertiesResource_GetMethod() { } util::Status PropertiesResource_GetMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_visibility_) { StrAppend(target, sep, "visibility=", client::CppValueToEscapedUrlValue( visibility_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PropertiesResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "propertyKey") { client::UriTemplate::AppendValue( property_key_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PropertiesResource_InsertMethod::PropertiesResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Property& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "files/{fileId}/properties"), file_id_(file_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. PropertiesResource_InsertMethod::~PropertiesResource_InsertMethod() { } util::Status PropertiesResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PropertiesResource_ListMethod::PropertiesResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{fileId}/properties"), file_id_(file_id.as_string()) { } // Standard destructor. PropertiesResource_ListMethod::~PropertiesResource_ListMethod() { } util::Status PropertiesResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PropertiesResource_PatchMethod::PropertiesResource_PatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key, const Property& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::PATCH, "files/{fileId}/properties/{propertyKey}"), file_id_(file_id.as_string()), property_key_(property_key.as_string()), visibility_("private"), _have_visibility_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. PropertiesResource_PatchMethod::~PropertiesResource_PatchMethod() { } util::Status PropertiesResource_PatchMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_visibility_) { StrAppend(target, sep, "visibility=", client::CppValueToEscapedUrlValue( visibility_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PropertiesResource_PatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "propertyKey") { client::UriTemplate::AppendValue( property_key_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. PropertiesResource_UpdateMethod::PropertiesResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key, const Property& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "files/{fileId}/properties/{propertyKey}"), file_id_(file_id.as_string()), property_key_(property_key.as_string()), visibility_("private"), _have_visibility_(false) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. PropertiesResource_UpdateMethod::~PropertiesResource_UpdateMethod() { } util::Status PropertiesResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_visibility_) { StrAppend(target, sep, "visibility=", client::CppValueToEscapedUrlValue( visibility_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status PropertiesResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "propertyKey") { client::UriTemplate::AppendValue( property_key_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. RealtimeResource_GetMethod::RealtimeResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{fileId}/realtime"), file_id_(file_id.as_string()), _have_revision_(false) { } // Standard destructor. RealtimeResource_GetMethod::~RealtimeResource_GetMethod() { } util::Status RealtimeResource_GetMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_revision_) { StrAppend(target, sep, "revision=", client::CppValueToEscapedUrlValue( revision_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status RealtimeResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // static const client::MediaUploadSpec RealtimeResource_UpdateMethod::SIMPLE_MEDIA_UPLOAD( "simple", "/upload/drive/v2/files/{fileId}/realtime", true); // static const client::MediaUploadSpec RealtimeResource_UpdateMethod::RESUMABLE_MEDIA_UPLOAD( "resumable", "/resumable/upload/drive/v2/files/{fileId}/realtime", true); // Standard constructor. RealtimeResource_UpdateMethod::RealtimeResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "files/{fileId}/realtime"), file_id_(file_id.as_string()), _have_base_revision_(false) { if (_media_content_reader_) { client::MediaUploader* uploader = new client::MediaUploader( &SIMPLE_MEDIA_UPLOAD, _service_->url_root(), client::JoinPath( _service_->url_path(), "files/{fileId}/realtime")); uploader->set_media_content_reader( _media_content_type_.as_string(), _media_content_reader_); ResetMediaUploader(uploader); } } // Standard destructor. RealtimeResource_UpdateMethod::~RealtimeResource_UpdateMethod() { } util::Status RealtimeResource_UpdateMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_base_revision_) { StrAppend(target, sep, "baseRevision=", client::CppValueToEscapedUrlValue( base_revision_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status RealtimeResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. RepliesResource_DeleteMethod::RepliesResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "files/{fileId}/comments/{commentId}/replies/{replyId}"), file_id_(file_id.as_string()), comment_id_(comment_id.as_string()), reply_id_(reply_id.as_string()) { } // Standard destructor. RepliesResource_DeleteMethod::~RepliesResource_DeleteMethod() { } util::Status RepliesResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "commentId") { client::UriTemplate::AppendValue( comment_id_, config, target); return client::StatusOk(); } if (variable_name == "replyId") { client::UriTemplate::AppendValue( reply_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. RepliesResource_GetMethod::RepliesResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{fileId}/comments/{commentId}/replies/{replyId}"), file_id_(file_id.as_string()), comment_id_(comment_id.as_string()), reply_id_(reply_id.as_string()), include_deleted_(false), _have_include_deleted_(false) { } // Standard destructor. RepliesResource_GetMethod::~RepliesResource_GetMethod() { } util::Status RepliesResource_GetMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_include_deleted_) { StrAppend(target, sep, "includeDeleted=", client::CppValueToEscapedUrlValue( include_deleted_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status RepliesResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "commentId") { client::UriTemplate::AppendValue( comment_id_, config, target); return client::StatusOk(); } if (variable_name == "replyId") { client::UriTemplate::AppendValue( reply_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. RepliesResource_InsertMethod::RepliesResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const CommentReply& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "files/{fileId}/comments/{commentId}/replies"), file_id_(file_id.as_string()), comment_id_(comment_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. RepliesResource_InsertMethod::~RepliesResource_InsertMethod() { } util::Status RepliesResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "commentId") { client::UriTemplate::AppendValue( comment_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. RepliesResource_ListMethod::RepliesResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{fileId}/comments/{commentId}/replies"), file_id_(file_id.as_string()), comment_id_(comment_id.as_string()), include_deleted_(false), max_results_(20), _have_include_deleted_(false), _have_max_results_(false), _have_page_token_(false) { } // Standard destructor. RepliesResource_ListMethod::~RepliesResource_ListMethod() { } util::Status RepliesResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_include_deleted_) { StrAppend(target, sep, "includeDeleted=", client::CppValueToEscapedUrlValue( include_deleted_)); sep = "&"; } if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status RepliesResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "commentId") { client::UriTemplate::AppendValue( comment_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. RepliesResource_PatchMethod::RepliesResource_PatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id, const CommentReply& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::PATCH, "files/{fileId}/comments/{commentId}/replies/{replyId}"), file_id_(file_id.as_string()), comment_id_(comment_id.as_string()), reply_id_(reply_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. RepliesResource_PatchMethod::~RepliesResource_PatchMethod() { } util::Status RepliesResource_PatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "commentId") { client::UriTemplate::AppendValue( comment_id_, config, target); return client::StatusOk(); } if (variable_name == "replyId") { client::UriTemplate::AppendValue( reply_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. RepliesResource_UpdateMethod::RepliesResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id, const CommentReply& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "files/{fileId}/comments/{commentId}/replies/{replyId}"), file_id_(file_id.as_string()), comment_id_(comment_id.as_string()), reply_id_(reply_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. RepliesResource_UpdateMethod::~RepliesResource_UpdateMethod() { } util::Status RepliesResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "commentId") { client::UriTemplate::AppendValue( comment_id_, config, target); return client::StatusOk(); } if (variable_name == "replyId") { client::UriTemplate::AppendValue( reply_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. RevisionsResource_DeleteMethod::RevisionsResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "files/{fileId}/revisions/{revisionId}"), file_id_(file_id.as_string()), revision_id_(revision_id.as_string()) { } // Standard destructor. RevisionsResource_DeleteMethod::~RevisionsResource_DeleteMethod() { } util::Status RevisionsResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "revisionId") { client::UriTemplate::AppendValue( revision_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. RevisionsResource_GetMethod::RevisionsResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{fileId}/revisions/{revisionId}"), file_id_(file_id.as_string()), revision_id_(revision_id.as_string()) { } // Standard destructor. RevisionsResource_GetMethod::~RevisionsResource_GetMethod() { } util::Status RevisionsResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "revisionId") { client::UriTemplate::AppendValue( revision_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. RevisionsResource_ListMethod::RevisionsResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "files/{fileId}/revisions"), file_id_(file_id.as_string()), max_results_(200), _have_max_results_(false), _have_page_token_(false) { } // Standard destructor. RevisionsResource_ListMethod::~RevisionsResource_ListMethod() { } util::Status RevisionsResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status RevisionsResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. RevisionsResource_PatchMethod::RevisionsResource_PatchMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id, const Revision& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::PATCH, "files/{fileId}/revisions/{revisionId}"), file_id_(file_id.as_string()), revision_id_(revision_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. RevisionsResource_PatchMethod::~RevisionsResource_PatchMethod() { } util::Status RevisionsResource_PatchMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "revisionId") { client::UriTemplate::AppendValue( revision_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. RevisionsResource_UpdateMethod::RevisionsResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id, const Revision& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "files/{fileId}/revisions/{revisionId}"), file_id_(file_id.as_string()), revision_id_(revision_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. RevisionsResource_UpdateMethod::~RevisionsResource_UpdateMethod() { } util::Status RevisionsResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "fileId") { client::UriTemplate::AppendValue( file_id_, config, target); return client::StatusOk(); } if (variable_name == "revisionId") { client::UriTemplate::AppendValue( revision_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. TeamdrivesResource_DeleteMethod::TeamdrivesResource_DeleteMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& team_drive_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::DELETE, "teamdrives/{teamDriveId}"), team_drive_id_(team_drive_id.as_string()) { } // Standard destructor. TeamdrivesResource_DeleteMethod::~TeamdrivesResource_DeleteMethod() { } util::Status TeamdrivesResource_DeleteMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "teamDriveId") { client::UriTemplate::AppendValue( team_drive_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. TeamdrivesResource_GetMethod::TeamdrivesResource_GetMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& team_drive_id) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "teamdrives/{teamDriveId}"), team_drive_id_(team_drive_id.as_string()) { } // Standard destructor. TeamdrivesResource_GetMethod::~TeamdrivesResource_GetMethod() { } util::Status TeamdrivesResource_GetMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "teamDriveId") { client::UriTemplate::AppendValue( team_drive_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. TeamdrivesResource_InsertMethod::TeamdrivesResource_InsertMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& request_id, const TeamDrive& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::POST, "teamdrives"), request_id_(request_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. TeamdrivesResource_InsertMethod::~TeamdrivesResource_InsertMethod() { } util::Status TeamdrivesResource_InsertMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; StrAppend(target, sep, "requestId=", client::CppValueToEscapedUrlValue( request_id_)); sep = "&"; return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status TeamdrivesResource_InsertMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. TeamdrivesResource_ListMethod::TeamdrivesResource_ListMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::GET, "teamdrives"), max_results_(10), _have_max_results_(false), _have_page_token_(false) { } // Standard destructor. TeamdrivesResource_ListMethod::~TeamdrivesResource_ListMethod() { } util::Status TeamdrivesResource_ListMethod::AppendOptionalQueryParameters(string* target) { const char* sep = (target->find('?') == string::npos) ? "?" : "&"; if (_have_max_results_) { StrAppend(target, sep, "maxResults=", client::CppValueToEscapedUrlValue( max_results_)); sep = "&"; } if (_have_page_token_) { StrAppend(target, sep, "pageToken=", client::CppValueToEscapedUrlValue( page_token_)); sep = "&"; } return DriveServiceBaseRequest::AppendOptionalQueryParameters(target); } util::Status TeamdrivesResource_ListMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } // Standard constructor. TeamdrivesResource_UpdateMethod::TeamdrivesResource_UpdateMethod( const DriveService* _service_, client::AuthorizationCredential* _credential_, const StringPiece& team_drive_id, const TeamDrive& __request_content__) : DriveServiceBaseRequest( _service_, _credential_, client::HttpRequest::PUT, "teamdrives/{teamDriveId}"), team_drive_id_(team_drive_id.as_string()) { AddJsonContentToRequest(&__request_content__); } // Standard destructor. TeamdrivesResource_UpdateMethod::~TeamdrivesResource_UpdateMethod() { } util::Status TeamdrivesResource_UpdateMethod::AppendVariable( const StringPiece& variable_name, const client::UriTemplateConfig& config, string* target) { if (variable_name == "teamDriveId") { client::UriTemplate::AppendValue( team_drive_id_, config, target); return client::StatusOk(); } return DriveServiceBaseRequest::AppendVariable( variable_name, config, target); } DriveService::DriveService(client::HttpTransport* transport) : ClientService("https://www.googleapis.com/", "drive/v2/", transport), about_(this), apps_(this), changes_(this), channels_(this), children_(this), comments_(this), files_(this), parents_(this), permissions_(this), properties_(this), realtime_(this), replies_(this), revisions_(this), teamdrives_(this) { } DriveService::~DriveService() { } DriveService::AboutResource::AboutResource(DriveService* service) : service_(service) { } AboutResource_GetMethod* DriveService::AboutResource::NewGetMethod(client::AuthorizationCredential* _credential_) const { return new AboutResource_GetMethod(service_, _credential_); } DriveService::AppsResource::AppsResource(DriveService* service) : service_(service) { } AppsResource_GetMethod* DriveService::AppsResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& app_id) const { return new AppsResource_GetMethod(service_, _credential_, app_id); } AppsResource_ListMethod* DriveService::AppsResource::NewListMethod(client::AuthorizationCredential* _credential_) const { return new AppsResource_ListMethod(service_, _credential_); } DriveService::ChangesResource::ChangesResource(DriveService* service) : service_(service) { } ChangesResource_GetMethod* DriveService::ChangesResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& change_id) const { return new ChangesResource_GetMethod(service_, _credential_, change_id); } ChangesResource_GetStartPageTokenMethod* DriveService::ChangesResource::NewGetStartPageTokenMethod(client::AuthorizationCredential* _credential_) const { return new ChangesResource_GetStartPageTokenMethod(service_, _credential_); } ChangesResource_ListMethod* DriveService::ChangesResource::NewListMethod(client::AuthorizationCredential* _credential_) const { return new ChangesResource_ListMethod(service_, _credential_); } ChangesResource_ListMethodPager* DriveService::ChangesResource::NewListMethodPager(client::AuthorizationCredential* _credential_) const { return new client::EncapsulatedServiceRequestPager<ChangesResource_ListMethod, ChangeList>(new ChangesResource_ListMethod(service_, _credential_)); } ChangesResource_WatchMethod* DriveService::ChangesResource::NewWatchMethod(client::AuthorizationCredential* _credential_, const Channel& __request_content__) const { return new ChangesResource_WatchMethod(service_, _credential_, __request_content__); } DriveService::ChannelsResource::ChannelsResource(DriveService* service) : service_(service) { } ChannelsResource_StopMethod* DriveService::ChannelsResource::NewStopMethod(client::AuthorizationCredential* _credential_, const Channel& __request_content__) const { return new ChannelsResource_StopMethod(service_, _credential_, __request_content__); } DriveService::ChildrenResource::ChildrenResource(DriveService* service) : service_(service) { } ChildrenResource_DeleteMethod* DriveService::ChildrenResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& folder_id, const StringPiece& child_id) const { return new ChildrenResource_DeleteMethod(service_, _credential_, folder_id, child_id); } ChildrenResource_GetMethod* DriveService::ChildrenResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& folder_id, const StringPiece& child_id) const { return new ChildrenResource_GetMethod(service_, _credential_, folder_id, child_id); } ChildrenResource_InsertMethod* DriveService::ChildrenResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& folder_id, const ChildReference& __request_content__) const { return new ChildrenResource_InsertMethod(service_, _credential_, folder_id, __request_content__); } ChildrenResource_ListMethod* DriveService::ChildrenResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& folder_id) const { return new ChildrenResource_ListMethod(service_, _credential_, folder_id); } ChildrenResource_ListMethodPager* DriveService::ChildrenResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& folder_id) const { return new client::EncapsulatedServiceRequestPager<ChildrenResource_ListMethod, ChildList>(new ChildrenResource_ListMethod(service_, _credential_, folder_id)); } DriveService::CommentsResource::CommentsResource(DriveService* service) : service_(service) { } CommentsResource_DeleteMethod* DriveService::CommentsResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id) const { return new CommentsResource_DeleteMethod(service_, _credential_, file_id, comment_id); } CommentsResource_GetMethod* DriveService::CommentsResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id) const { return new CommentsResource_GetMethod(service_, _credential_, file_id, comment_id); } CommentsResource_InsertMethod* DriveService::CommentsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Comment& __request_content__) const { return new CommentsResource_InsertMethod(service_, _credential_, file_id, __request_content__); } CommentsResource_ListMethod* DriveService::CommentsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id) const { return new CommentsResource_ListMethod(service_, _credential_, file_id); } CommentsResource_ListMethodPager* DriveService::CommentsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& file_id) const { return new client::EncapsulatedServiceRequestPager<CommentsResource_ListMethod, CommentList>(new CommentsResource_ListMethod(service_, _credential_, file_id)); } CommentsResource_PatchMethod* DriveService::CommentsResource::NewPatchMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const Comment& __request_content__) const { return new CommentsResource_PatchMethod(service_, _credential_, file_id, comment_id, __request_content__); } CommentsResource_UpdateMethod* DriveService::CommentsResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const Comment& __request_content__) const { return new CommentsResource_UpdateMethod(service_, _credential_, file_id, comment_id, __request_content__); } DriveService::FilesResource::FilesResource(DriveService* service) : service_(service) { } FilesResource_CopyMethod* DriveService::FilesResource::NewCopyMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const File& __request_content__) const { return new FilesResource_CopyMethod(service_, _credential_, file_id, __request_content__); } FilesResource_DeleteMethod* DriveService::FilesResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id) const { return new FilesResource_DeleteMethod(service_, _credential_, file_id); } FilesResource_EmptyTrashMethod* DriveService::FilesResource::NewEmptyTrashMethod(client::AuthorizationCredential* _credential_) const { return new FilesResource_EmptyTrashMethod(service_, _credential_); } FilesResource_ExportMethod* DriveService::FilesResource::NewExportMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& mime_type) const { return new FilesResource_ExportMethod(service_, _credential_, file_id, mime_type); } FilesResource_GenerateIdsMethod* DriveService::FilesResource::NewGenerateIdsMethod(client::AuthorizationCredential* _credential_) const { return new FilesResource_GenerateIdsMethod(service_, _credential_); } FilesResource_GetMethod* DriveService::FilesResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id) const { return new FilesResource_GetMethod(service_, _credential_, file_id); } // This factory method is deprecated in favor of the newer variation that // also takes the media upload parameters. FilesResource_InsertMethod* DriveService::FilesResource::NewInsertMethod(client::AuthorizationCredential* _credential_) const { return new FilesResource_InsertMethod(service_, _credential_); } FilesResource_InsertMethod* DriveService::FilesResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const File* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const { return new FilesResource_InsertMethod(service_, _credential_, _metadata_, _media_content_type_, _media_content_reader_); } FilesResource_ListMethod* DriveService::FilesResource::NewListMethod(client::AuthorizationCredential* _credential_) const { return new FilesResource_ListMethod(service_, _credential_); } FilesResource_ListMethodPager* DriveService::FilesResource::NewListMethodPager(client::AuthorizationCredential* _credential_) const { return new client::EncapsulatedServiceRequestPager<FilesResource_ListMethod, FileList>(new FilesResource_ListMethod(service_, _credential_)); } FilesResource_PatchMethod* DriveService::FilesResource::NewPatchMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const File& __request_content__) const { return new FilesResource_PatchMethod(service_, _credential_, file_id, __request_content__); } FilesResource_TouchMethod* DriveService::FilesResource::NewTouchMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id) const { return new FilesResource_TouchMethod(service_, _credential_, file_id); } FilesResource_TrashMethod* DriveService::FilesResource::NewTrashMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id) const { return new FilesResource_TrashMethod(service_, _credential_, file_id); } FilesResource_UntrashMethod* DriveService::FilesResource::NewUntrashMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id) const { return new FilesResource_UntrashMethod(service_, _credential_, file_id); } // This factory method is deprecated in favor of the newer variation that // also takes the media upload parameters. FilesResource_UpdateMethod* DriveService::FilesResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id) const { return new FilesResource_UpdateMethod(service_, _credential_, file_id); } FilesResource_UpdateMethod* DriveService::FilesResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const File* _metadata_, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const { return new FilesResource_UpdateMethod(service_, _credential_, file_id, _metadata_, _media_content_type_, _media_content_reader_); } FilesResource_WatchMethod* DriveService::FilesResource::NewWatchMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Channel& __request_content__) const { return new FilesResource_WatchMethod(service_, _credential_, file_id, __request_content__); } DriveService::ParentsResource::ParentsResource(DriveService* service) : service_(service) { } ParentsResource_DeleteMethod* DriveService::ParentsResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& parent_id) const { return new ParentsResource_DeleteMethod(service_, _credential_, file_id, parent_id); } ParentsResource_GetMethod* DriveService::ParentsResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& parent_id) const { return new ParentsResource_GetMethod(service_, _credential_, file_id, parent_id); } ParentsResource_InsertMethod* DriveService::ParentsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const ParentReference& __request_content__) const { return new ParentsResource_InsertMethod(service_, _credential_, file_id, __request_content__); } ParentsResource_ListMethod* DriveService::ParentsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id) const { return new ParentsResource_ListMethod(service_, _credential_, file_id); } DriveService::PermissionsResource::PermissionsResource(DriveService* service) : service_(service) { } PermissionsResource_DeleteMethod* DriveService::PermissionsResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id) const { return new PermissionsResource_DeleteMethod(service_, _credential_, file_id, permission_id); } PermissionsResource_GetMethod* DriveService::PermissionsResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id) const { return new PermissionsResource_GetMethod(service_, _credential_, file_id, permission_id); } PermissionsResource_GetIdForEmailMethod* DriveService::PermissionsResource::NewGetIdForEmailMethod(client::AuthorizationCredential* _credential_, const StringPiece& email) const { return new PermissionsResource_GetIdForEmailMethod(service_, _credential_, email); } PermissionsResource_InsertMethod* DriveService::PermissionsResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Permission& __request_content__) const { return new PermissionsResource_InsertMethod(service_, _credential_, file_id, __request_content__); } PermissionsResource_ListMethod* DriveService::PermissionsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id) const { return new PermissionsResource_ListMethod(service_, _credential_, file_id); } PermissionsResource_ListMethodPager* DriveService::PermissionsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& file_id) const { return new client::EncapsulatedServiceRequestPager<PermissionsResource_ListMethod, PermissionList>(new PermissionsResource_ListMethod(service_, _credential_, file_id)); } PermissionsResource_PatchMethod* DriveService::PermissionsResource::NewPatchMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id, const Permission& __request_content__) const { return new PermissionsResource_PatchMethod(service_, _credential_, file_id, permission_id, __request_content__); } PermissionsResource_UpdateMethod* DriveService::PermissionsResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& permission_id, const Permission& __request_content__) const { return new PermissionsResource_UpdateMethod(service_, _credential_, file_id, permission_id, __request_content__); } DriveService::PropertiesResource::PropertiesResource(DriveService* service) : service_(service) { } PropertiesResource_DeleteMethod* DriveService::PropertiesResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key) const { return new PropertiesResource_DeleteMethod(service_, _credential_, file_id, property_key); } PropertiesResource_GetMethod* DriveService::PropertiesResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key) const { return new PropertiesResource_GetMethod(service_, _credential_, file_id, property_key); } PropertiesResource_InsertMethod* DriveService::PropertiesResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const Property& __request_content__) const { return new PropertiesResource_InsertMethod(service_, _credential_, file_id, __request_content__); } PropertiesResource_ListMethod* DriveService::PropertiesResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id) const { return new PropertiesResource_ListMethod(service_, _credential_, file_id); } PropertiesResource_PatchMethod* DriveService::PropertiesResource::NewPatchMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key, const Property& __request_content__) const { return new PropertiesResource_PatchMethod(service_, _credential_, file_id, property_key, __request_content__); } PropertiesResource_UpdateMethod* DriveService::PropertiesResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& property_key, const Property& __request_content__) const { return new PropertiesResource_UpdateMethod(service_, _credential_, file_id, property_key, __request_content__); } DriveService::RealtimeResource::RealtimeResource(DriveService* service) : service_(service) { } RealtimeResource_GetMethod* DriveService::RealtimeResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id) const { return new RealtimeResource_GetMethod(service_, _credential_, file_id); } RealtimeResource_UpdateMethod* DriveService::RealtimeResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& _media_content_type_, client::DataReader* _media_content_reader_) const { return new RealtimeResource_UpdateMethod(service_, _credential_, file_id, _media_content_type_, _media_content_reader_); } DriveService::RepliesResource::RepliesResource(DriveService* service) : service_(service) { } RepliesResource_DeleteMethod* DriveService::RepliesResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id) const { return new RepliesResource_DeleteMethod(service_, _credential_, file_id, comment_id, reply_id); } RepliesResource_GetMethod* DriveService::RepliesResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id) const { return new RepliesResource_GetMethod(service_, _credential_, file_id, comment_id, reply_id); } RepliesResource_InsertMethod* DriveService::RepliesResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const CommentReply& __request_content__) const { return new RepliesResource_InsertMethod(service_, _credential_, file_id, comment_id, __request_content__); } RepliesResource_ListMethod* DriveService::RepliesResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id) const { return new RepliesResource_ListMethod(service_, _credential_, file_id, comment_id); } RepliesResource_ListMethodPager* DriveService::RepliesResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id) const { return new client::EncapsulatedServiceRequestPager<RepliesResource_ListMethod, CommentReplyList>(new RepliesResource_ListMethod(service_, _credential_, file_id, comment_id)); } RepliesResource_PatchMethod* DriveService::RepliesResource::NewPatchMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id, const CommentReply& __request_content__) const { return new RepliesResource_PatchMethod(service_, _credential_, file_id, comment_id, reply_id, __request_content__); } RepliesResource_UpdateMethod* DriveService::RepliesResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& comment_id, const StringPiece& reply_id, const CommentReply& __request_content__) const { return new RepliesResource_UpdateMethod(service_, _credential_, file_id, comment_id, reply_id, __request_content__); } DriveService::RevisionsResource::RevisionsResource(DriveService* service) : service_(service) { } RevisionsResource_DeleteMethod* DriveService::RevisionsResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id) const { return new RevisionsResource_DeleteMethod(service_, _credential_, file_id, revision_id); } RevisionsResource_GetMethod* DriveService::RevisionsResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id) const { return new RevisionsResource_GetMethod(service_, _credential_, file_id, revision_id); } RevisionsResource_ListMethod* DriveService::RevisionsResource::NewListMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id) const { return new RevisionsResource_ListMethod(service_, _credential_, file_id); } RevisionsResource_ListMethodPager* DriveService::RevisionsResource::NewListMethodPager(client::AuthorizationCredential* _credential_, const StringPiece& file_id) const { return new client::EncapsulatedServiceRequestPager<RevisionsResource_ListMethod, RevisionList>(new RevisionsResource_ListMethod(service_, _credential_, file_id)); } RevisionsResource_PatchMethod* DriveService::RevisionsResource::NewPatchMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id, const Revision& __request_content__) const { return new RevisionsResource_PatchMethod(service_, _credential_, file_id, revision_id, __request_content__); } RevisionsResource_UpdateMethod* DriveService::RevisionsResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& file_id, const StringPiece& revision_id, const Revision& __request_content__) const { return new RevisionsResource_UpdateMethod(service_, _credential_, file_id, revision_id, __request_content__); } DriveService::TeamdrivesResource::TeamdrivesResource(DriveService* service) : service_(service) { } TeamdrivesResource_DeleteMethod* DriveService::TeamdrivesResource::NewDeleteMethod(client::AuthorizationCredential* _credential_, const StringPiece& team_drive_id) const { return new TeamdrivesResource_DeleteMethod(service_, _credential_, team_drive_id); } TeamdrivesResource_GetMethod* DriveService::TeamdrivesResource::NewGetMethod(client::AuthorizationCredential* _credential_, const StringPiece& team_drive_id) const { return new TeamdrivesResource_GetMethod(service_, _credential_, team_drive_id); } TeamdrivesResource_InsertMethod* DriveService::TeamdrivesResource::NewInsertMethod(client::AuthorizationCredential* _credential_, const StringPiece& request_id, const TeamDrive& __request_content__) const { return new TeamdrivesResource_InsertMethod(service_, _credential_, request_id, __request_content__); } TeamdrivesResource_ListMethod* DriveService::TeamdrivesResource::NewListMethod(client::AuthorizationCredential* _credential_) const { return new TeamdrivesResource_ListMethod(service_, _credential_); } TeamdrivesResource_ListMethodPager* DriveService::TeamdrivesResource::NewListMethodPager(client::AuthorizationCredential* _credential_) const { return new client::EncapsulatedServiceRequestPager<TeamdrivesResource_ListMethod, TeamDriveList>(new TeamdrivesResource_ListMethod(service_, _credential_)); } TeamdrivesResource_UpdateMethod* DriveService::TeamdrivesResource::NewUpdateMethod(client::AuthorizationCredential* _credential_, const StringPiece& team_drive_id, const TeamDrive& __request_content__) const { return new TeamdrivesResource_UpdateMethod(service_, _credential_, team_drive_id, __request_content__); } } // namespace google_drive_api <file_sep>/src/googleapis/client/service/client_service.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <iostream> using std::cout; using std::endl; using std::ostream; // NOLINT #include <string> using std::string; #include <sstream> #include <glog/logging.h> #include "googleapis/client/data/serializable_json.h" #include "googleapis/client/service/client_service.h" #include "googleapis/client/service/media_uploader.h" #include "googleapis/client/transport/http_request.h" #include "googleapis/client/transport/http_request_batch.h" #include "googleapis/client/transport/http_response.h" #include "googleapis/client/transport/http_transport.h" #include "googleapis/client/util/status.h" #include "googleapis/client/util/uri_template.h" #include "googleapis/client/util/uri_utils.h" #include "googleapis/strings/stringpiece.h" namespace googleapis { namespace client { ClientServiceRequest::ClientServiceRequest( const ClientService* service, AuthorizationCredential* credential, const HttpRequest::HttpMethod& method, const StringPiece& uri_template) : http_request_(nullptr), destroy_when_done_(false), use_media_download_(false) { if (service->in_shutdown()) { return; } uri_template_ = service->service_url(); uri_template_.append(uri_template.as_string()); http_request_.reset(service->transport()->NewHttpRequest(method)); http_request_->set_credential(credential); // can be NULL // We own the request so make sure it wont auto destroy http_request_->mutable_options()->set_destroy_when_done(false); } ClientServiceRequest::~ClientServiceRequest() { } HttpRequest* ClientServiceRequest::ConvertToHttpRequestAndDestroy() { if (http_request_ == nullptr) { delete this; return nullptr; } googleapis::util::Status status = PrepareHttpRequest(); if (!status.ok()) { LOG(WARNING) << "Error preparing request: " << status.error_message(); http_request_->mutable_state()->set_transport_status(status); } HttpRequest* result = http_request_.release(); delete this; return result; } HttpRequest* ClientServiceRequest::ConvertIntoHttpRequestBatchAndDestroy( HttpRequestBatch* batch, HttpRequestCallback* callback) { HttpRequest* http_request = ConvertToHttpRequestAndDestroy(); if (http_request == nullptr) return nullptr; return batch->AddFromGenericRequestAndRetire(http_request, callback); } void ClientServiceRequest::DestroyWhenDone() { if (http_request_ != nullptr && http_request_->state().done()) { // Avoid race condition if we're destroying this while the underlying // request isnt ready to be deleted. HttpRequest* request = http_request_.release(); if (request) { request->DestroyWhenDone(); } delete this; } else { destroy_when_done_ = true; } } util::Status ClientServiceRequest::PrepareHttpRequest() { if (http_request_ == nullptr) { return StatusCanceled("shutdown"); } string url; googleapis::util::Status status = PrepareUrl(uri_template_, &url); http_request_->set_url(url); VLOG(1) << "Prepared url:" << url; return status; } util::Status ClientServiceRequest::PrepareUrl( const StringPiece& templated_url, string* prepared_url) { std::unique_ptr<UriTemplate::AppendVariableCallback> callback( NewPermanentCallback(this, &ClientServiceRequest::CallAppendVariable)); // Attempt to expand everything for best effort. googleapis::util::Status expand_status = UriTemplate::Expand( templated_url.as_string(), callback.get(), prepared_url); googleapis::util::Status query_status = AppendOptionalQueryParameters(prepared_url); return expand_status.ok() ? query_status : expand_status; } util::Status ClientServiceRequest::Execute() { if (http_request_ == nullptr) { return StatusCanceled("shutdown"); } if (uploader_.get()) { return this->ExecuteWithUploader(); } googleapis::util::Status status = PrepareHttpRequest(); if (!status.ok()) { http_request_->WillNotExecute(status); return status; } status = http_request_->Execute(); if (destroy_when_done_) { VLOG(1) << "Auto-destroying " << this; delete this; } return status; } util::Status ClientServiceRequest::ExecuteWithUploader() { if (http_request_ == nullptr) { return StatusCanceled("shutdown"); } client::HttpRequest* request = mutable_http_request(); googleapis::util::Status status = uploader_->BuildRequest( request, NewCallback(this, &ClientServiceRequest::PrepareUrl)); if (!status.ok()) { return status; } return uploader_->Upload(request); } util::Status ClientServiceRequest::ExecuteAndParseResponse( SerializableJson* data) { bool destroy_when_done = destroy_when_done_; destroy_when_done_ = false; googleapis::util::Status result = Execute(); if (result.ok()) { result = ParseResponse(http_response(), data); } if (destroy_when_done) { delete this; } return result; } void ClientServiceRequest::CallbackThenDestroy( HttpRequestCallback* callback, HttpRequest* request) { callback->Run(request); VLOG(1) << "Auto-deleting request because it is done."; if (http_request_ != nullptr) { // TODO(user): 20130318 // This is called by HttpRequest::Execute via DoExecute which expects the // request to still be valid so it can auto-destroy. Maybe I should cache // that value before calling the callback to permit the callback to destroy // the request, as it does here. In the meantime we'll detach the // http request object so it can self destruct. Otherwise if we destroy it // here, the caller will implode from having the object deleted when it goes // to check whether it should destroy it or not. http_request_->mutable_options()->set_destroy_when_done(true); http_request_.release(); } delete this; } void ClientServiceRequest::ExecuteAsync(HttpRequestCallback* callback) { if (destroy_when_done_) { // If we want to destroy the request when we're done then chain the // callback into one that will destroy this request instance. VLOG(1) << "Will intercept request callback to auto-delete"; HttpRequestCallback* destroy_request = NewCallback(this, &ClientServiceRequest::CallbackThenDestroy, callback); callback = destroy_request; } if (http_request_ == nullptr) { if (callback) { callback->Run(nullptr); } return; } if (callback) { // bind the callback here so if PrepareHttpRequest fails then we // can notify the callback. http_request_->set_callback(callback); } googleapis::util::Status status; if (uploader_.get()) { status = uploader_->BuildRequest( http_request_.get(), NewCallback(this, &ClientServiceRequest::PrepareUrl)); } else { status = PrepareHttpRequest(); } if (!status.ok()) { http_request_->WillNotExecute(status); return; } // We already bound the callback, so it does not have to be passed to the // executor. if (uploader_.get()) { uploader_->UploadAsync(http_request_.get(), NULL); } else { http_request_->ExecuteAsync(NULL); } } // static util::Status ClientServiceRequest::ParseResponse( HttpResponse* response, SerializableJson* data) { data->Clear(); if (!response->status().ok()) return response->status(); DataReader* reader = response->body_reader(); if (!reader) { return StatusInternalError("Response has no body to parse."); } return data->LoadFromJsonReader(reader); } util::Status ClientServiceRequest::AppendVariable( const StringPiece& variable_name, const UriTemplateConfig& config, string* target) { LOG(FATAL) << "Either override AppendVariable or PrepareHttpRequest"; return StatusUnimplemented("Internal error"); } util::Status ClientServiceRequest::AppendOptionalQueryParameters( string* target) { const char* sep = "?"; if (use_media_download_) { const char kAlt[] = "alt="; bool have_alt = false; int begin_params = target->find('?'); if (begin_params != string::npos) { sep = "&"; for (int offset = target->find(kAlt, begin_params + 1); offset != string::npos; offset = target->find(kAlt, offset + 1)) { char prev = target->c_str()[offset - 1]; if (prev != '?' && prev != '&') continue; StringPiece value(StringPiece(*target).substr(offset + sizeof(kAlt))); if (value == "media" || value.starts_with("media&")) { // That second check means that the value was 'media' and then // another parameter is being declared within the url. have_alt = true; } else { LOG(WARNING) << "alt parameter was already specified in url=" << *target << " which is inconsistent with 'media' for media-download"; have_alt = true; } } } if (!have_alt) { target->append(sep); target->append("alt=media"); sep = "&"; } } return StatusOk(); } util::Status ClientServiceRequest::CallAppendVariable( const string& variable_name, const UriTemplateConfig& config, string* target) { googleapis::util::Status status = AppendVariable(variable_name, config, target); if (!status.ok()) { VLOG(1) << "Failed appending variable_name='" << variable_name << "'"; } return status; } void ClientServiceRequest::ResetMediaUploader(MediaUploader* uploader) { return uploader_.reset(uploader); } ClientService::ClientService( const StringPiece& url_root, const StringPiece& url_path, HttpTransport* transport) : transport_(transport), in_shutdown_(false) { ChangeServiceUrl(url_root, url_path); } ClientService::~ClientService() { } void ClientService::Shutdown() { in_shutdown_ = true; transport_->Shutdown(); } void ClientService::ChangeServiceUrl( const StringPiece& url_root, const StringPiece& url_path) { // We're going to standardize so that: // url root always ends with '/' // url path never begins with '/' // But we're not necessarily going to document it this way yet. int url_root_extra = url_root.ends_with("/") ? 0 : 1; int url_path_trim = url_path.starts_with("/") ? 1 : 0; service_url_ = JoinPath(url_root.as_string(), url_path.as_string()); url_root_ = StringPiece(service_url_).substr(0, url_root.size() + url_root_extra); url_path_ = StringPiece(service_url_) .substr(url_root_.size(), url_path.size() - url_path_trim); } } // namespace client } // namespace googleapis <file_sep>/service_apis/drive/google/drive_api/permission.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // Drive API (drive/v2) // Generated from: // Version: v2 // Revision: 20170512 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_DRIVE_API_PERMISSION_H_ #define GOOGLE_DRIVE_API_PERMISSION_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_drive_api { using namespace googleapis; /** * A permission for a file. * * @ingroup DataObject */ class Permission : public client::JsonCppData { public: /** * No description provided. * * @ingroup DataObject */ class PermissionTeamDrivePermissionDetails : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static PermissionTeamDrivePermissionDetails* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit PermissionTeamDrivePermissionDetails(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit PermissionTeamDrivePermissionDetails(Json::Value* storage); /** * Standard destructor. */ virtual ~PermissionTeamDrivePermissionDetails(); /** * Returns a string denoting the type of this data object. * * @return * <code>google_drive_api::PermissionTeamDrivePermissionDetails</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::PermissionTeamDrivePermissionDetails"); } /** * Determine if the '<code>additionalRoles</code>' attribute was set. * * @return true if the '<code>additionalRoles</code>' attribute was set. */ bool has_additional_roles() const { return Storage().isMember("additionalRoles"); } /** * Clears the '<code>additionalRoles</code>' attribute. */ void clear_additional_roles() { MutableStorage()->removeMember("additionalRoles"); } /** * Get a reference to the value of the '<code>additionalRoles</code>' * attribute. */ const client::JsonCppArray<string > get_additional_roles() const { const Json::Value& storage = Storage("additionalRoles"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>additionalRoles</code>' * property. * * Additional roles for this user. Only commenter is currently possible, * though more may be supported in the future. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_additionalRoles() { Json::Value* storage = MutableStorage("additionalRoles"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>inherited</code>' attribute was set. * * @return true if the '<code>inherited</code>' attribute was set. */ bool has_inherited() const { return Storage().isMember("inherited"); } /** * Clears the '<code>inherited</code>' attribute. */ void clear_inherited() { MutableStorage()->removeMember("inherited"); } /** * Get the value of the '<code>inherited</code>' attribute. */ bool get_inherited() const { const Json::Value& storage = Storage("inherited"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>inherited</code>' attribute. * * Whether this permission is inherited. This field is always populated. * This is an output-only field. * * @param[in] value The new value. */ void set_inherited(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("inherited")); } /** * Determine if the '<code>inheritedFrom</code>' attribute was set. * * @return true if the '<code>inheritedFrom</code>' attribute was set. */ bool has_inherited_from() const { return Storage().isMember("inheritedFrom"); } /** * Clears the '<code>inheritedFrom</code>' attribute. */ void clear_inherited_from() { MutableStorage()->removeMember("inheritedFrom"); } /** * Get the value of the '<code>inheritedFrom</code>' attribute. */ const StringPiece get_inherited_from() const { const Json::Value& v = Storage("inheritedFrom"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>inheritedFrom</code>' attribute. * * The ID of the item from which this permission is inherited. This is an * output-only field and is only populated for members of the Team Drive. * * @param[in] value The new value. */ void set_inherited_from(const StringPiece& value) { *MutableStorage("inheritedFrom") = value.data(); } /** * Determine if the '<code>role</code>' attribute was set. * * @return true if the '<code>role</code>' attribute was set. */ bool has_role() const { return Storage().isMember("role"); } /** * Clears the '<code>role</code>' attribute. */ void clear_role() { MutableStorage()->removeMember("role"); } /** * Get the value of the '<code>role</code>' attribute. */ const StringPiece get_role() const { const Json::Value& v = Storage("role"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>role</code>' attribute. * * The primary role for this user. While new values may be added in the * future, the following are currently possible: * - organizer * - reader * - writer. * * @param[in] value The new value. */ void set_role(const StringPiece& value) { *MutableStorage("role") = value.data(); } /** * Determine if the '<code>teamDrivePermissionType</code>' attribute was * set. * * @return true if the '<code>teamDrivePermissionType</code>' attribute was * set. */ bool has_team_drive_permission_type() const { return Storage().isMember("teamDrivePermissionType"); } /** * Clears the '<code>teamDrivePermissionType</code>' attribute. */ void clear_team_drive_permission_type() { MutableStorage()->removeMember("teamDrivePermissionType"); } /** * Get the value of the '<code>teamDrivePermissionType</code>' attribute. */ const StringPiece get_team_drive_permission_type() const { const Json::Value& v = Storage("teamDrivePermissionType"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>teamDrivePermissionType</code>' attribute. * * The Team Drive permission type for this user. While new values may be * added in future, the following are currently possible: * - file * - member. * * @param[in] value The new value. */ void set_team_drive_permission_type(const StringPiece& value) { *MutableStorage("teamDrivePermissionType") = value.data(); } private: void operator=(const PermissionTeamDrivePermissionDetails&); }; // PermissionTeamDrivePermissionDetails /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static Permission* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Permission(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit Permission(Json::Value* storage); /** * Standard destructor. */ virtual ~Permission(); /** * Returns a string denoting the type of this data object. * * @return <code>google_drive_api::Permission</code> */ const StringPiece GetTypeName() const { return StringPiece("google_drive_api::Permission"); } /** * Determine if the '<code>additionalRoles</code>' attribute was set. * * @return true if the '<code>additionalRoles</code>' attribute was set. */ bool has_additional_roles() const { return Storage().isMember("additionalRoles"); } /** * Clears the '<code>additionalRoles</code>' attribute. */ void clear_additional_roles() { MutableStorage()->removeMember("additionalRoles"); } /** * Get a reference to the value of the '<code>additionalRoles</code>' * attribute. */ const client::JsonCppArray<string > get_additional_roles() const { const Json::Value& storage = Storage("additionalRoles"); return client::JsonValueToCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Gets a reference to a mutable value of the '<code>additionalRoles</code>' * property. * * Additional roles for this user. Only commenter is currently allowed, though * more may be supported in the future. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<string > mutable_additionalRoles() { Json::Value* storage = MutableStorage("additionalRoles"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<string > >(storage); } /** * Determine if the '<code>authKey</code>' attribute was set. * * @return true if the '<code>authKey</code>' attribute was set. */ bool has_auth_key() const { return Storage().isMember("authKey"); } /** * Clears the '<code>authKey</code>' attribute. */ void clear_auth_key() { MutableStorage()->removeMember("authKey"); } /** * Get the value of the '<code>authKey</code>' attribute. */ const StringPiece get_auth_key() const { const Json::Value& v = Storage("authKey"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>authKey</code>' attribute. * * The authkey parameter required for this permission. * * @param[in] value The new value. */ void set_auth_key(const StringPiece& value) { *MutableStorage("authKey") = value.data(); } /** * Determine if the '<code>deleted</code>' attribute was set. * * @return true if the '<code>deleted</code>' attribute was set. */ bool has_deleted() const { return Storage().isMember("deleted"); } /** * Clears the '<code>deleted</code>' attribute. */ void clear_deleted() { MutableStorage()->removeMember("deleted"); } /** * Get the value of the '<code>deleted</code>' attribute. */ bool get_deleted() const { const Json::Value& storage = Storage("deleted"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>deleted</code>' attribute. * * Whether the account associated with this permission has been deleted. This * field only pertains to user and group permissions. * * @param[in] value The new value. */ void set_deleted(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("deleted")); } /** * Determine if the '<code>domain</code>' attribute was set. * * @return true if the '<code>domain</code>' attribute was set. */ bool has_domain() const { return Storage().isMember("domain"); } /** * Clears the '<code>domain</code>' attribute. */ void clear_domain() { MutableStorage()->removeMember("domain"); } /** * Get the value of the '<code>domain</code>' attribute. */ const StringPiece get_domain() const { const Json::Value& v = Storage("domain"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>domain</code>' attribute. * * The domain name of the entity this permission refers to. This is an output- * only field which is present when the permission type is user, group or * domain. * * @param[in] value The new value. */ void set_domain(const StringPiece& value) { *MutableStorage("domain") = value.data(); } /** * Determine if the '<code>emailAddress</code>' attribute was set. * * @return true if the '<code>emailAddress</code>' attribute was set. */ bool has_email_address() const { return Storage().isMember("emailAddress"); } /** * Clears the '<code>emailAddress</code>' attribute. */ void clear_email_address() { MutableStorage()->removeMember("emailAddress"); } /** * Get the value of the '<code>emailAddress</code>' attribute. */ const StringPiece get_email_address() const { const Json::Value& v = Storage("emailAddress"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>emailAddress</code>' attribute. * * The email address of the user or group this permission refers to. This is * an output-only field which is present when the permission type is user or * group. * * @param[in] value The new value. */ void set_email_address(const StringPiece& value) { *MutableStorage("emailAddress") = value.data(); } /** * Determine if the '<code>etag</code>' attribute was set. * * @return true if the '<code>etag</code>' attribute was set. */ bool has_etag() const { return Storage().isMember("etag"); } /** * Clears the '<code>etag</code>' attribute. */ void clear_etag() { MutableStorage()->removeMember("etag"); } /** * Get the value of the '<code>etag</code>' attribute. */ const StringPiece get_etag() const { const Json::Value& v = Storage("etag"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>etag</code>' attribute. * * The ETag of the permission. * * @param[in] value The new value. */ void set_etag(const StringPiece& value) { *MutableStorage("etag") = value.data(); } /** * Determine if the '<code>expirationDate</code>' attribute was set. * * @return true if the '<code>expirationDate</code>' attribute was set. */ bool has_expiration_date() const { return Storage().isMember("expirationDate"); } /** * Clears the '<code>expirationDate</code>' attribute. */ void clear_expiration_date() { MutableStorage()->removeMember("expirationDate"); } /** * Get the value of the '<code>expirationDate</code>' attribute. */ client::DateTime get_expiration_date() const { const Json::Value& storage = Storage("expirationDate"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>expirationDate</code>' attribute. * * The time at which this permission will expire (RFC 3339 date-time). * Expiration dates have the following restrictions: * - They can only be set on user and group permissions * - The date must be in the future * - The date cannot be more than a year in the future * - The date can only be set on drive.permissions.update requests. * * @param[in] value The new value. */ void set_expiration_date(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("expirationDate")); } /** * Determine if the '<code>id</code>' attribute was set. * * @return true if the '<code>id</code>' attribute was set. */ bool has_id() const { return Storage().isMember("id"); } /** * Clears the '<code>id</code>' attribute. */ void clear_id() { MutableStorage()->removeMember("id"); } /** * Get the value of the '<code>id</code>' attribute. */ const StringPiece get_id() const { const Json::Value& v = Storage("id"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>id</code>' attribute. * * The ID of the user this permission refers to, and identical to the * permissionId in the About and Files resources. When making a * drive.permissions.insert request, exactly one of the id or value fields * must be specified unless the permission type is anyone, in which case both * id and value are ignored. * * @param[in] value The new value. */ void set_id(const StringPiece& value) { *MutableStorage("id") = value.data(); } /** * Determine if the '<code>kind</code>' attribute was set. * * @return true if the '<code>kind</code>' attribute was set. */ bool has_kind() const { return Storage().isMember("kind"); } /** * Clears the '<code>kind</code>' attribute. */ void clear_kind() { MutableStorage()->removeMember("kind"); } /** * Get the value of the '<code>kind</code>' attribute. */ const StringPiece get_kind() const { const Json::Value& v = Storage("kind"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>kind</code>' attribute. * * This is always drive#permission. * * @param[in] value The new value. */ void set_kind(const StringPiece& value) { *MutableStorage("kind") = value.data(); } /** * Determine if the '<code>name</code>' attribute was set. * * @return true if the '<code>name</code>' attribute was set. */ bool has_name() const { return Storage().isMember("name"); } /** * Clears the '<code>name</code>' attribute. */ void clear_name() { MutableStorage()->removeMember("name"); } /** * Get the value of the '<code>name</code>' attribute. */ const StringPiece get_name() const { const Json::Value& v = Storage("name"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>name</code>' attribute. * * The name for this permission. * * @param[in] value The new value. */ void set_name(const StringPiece& value) { *MutableStorage("name") = value.data(); } /** * Determine if the '<code>photoLink</code>' attribute was set. * * @return true if the '<code>photoLink</code>' attribute was set. */ bool has_photo_link() const { return Storage().isMember("photoLink"); } /** * Clears the '<code>photoLink</code>' attribute. */ void clear_photo_link() { MutableStorage()->removeMember("photoLink"); } /** * Get the value of the '<code>photoLink</code>' attribute. */ const StringPiece get_photo_link() const { const Json::Value& v = Storage("photoLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>photoLink</code>' attribute. * * A link to the profile photo, if available. * * @param[in] value The new value. */ void set_photo_link(const StringPiece& value) { *MutableStorage("photoLink") = value.data(); } /** * Determine if the '<code>role</code>' attribute was set. * * @return true if the '<code>role</code>' attribute was set. */ bool has_role() const { return Storage().isMember("role"); } /** * Clears the '<code>role</code>' attribute. */ void clear_role() { MutableStorage()->removeMember("role"); } /** * Get the value of the '<code>role</code>' attribute. */ const StringPiece get_role() const { const Json::Value& v = Storage("role"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>role</code>' attribute. * * The primary role for this user. While new values may be supported in the * future, the following are currently allowed: * - organizer * - owner * - reader * - writer. * * @param[in] value The new value. */ void set_role(const StringPiece& value) { *MutableStorage("role") = value.data(); } /** * Determine if the '<code>selfLink</code>' attribute was set. * * @return true if the '<code>selfLink</code>' attribute was set. */ bool has_self_link() const { return Storage().isMember("selfLink"); } /** * Clears the '<code>selfLink</code>' attribute. */ void clear_self_link() { MutableStorage()->removeMember("selfLink"); } /** * Get the value of the '<code>selfLink</code>' attribute. */ const StringPiece get_self_link() const { const Json::Value& v = Storage("selfLink"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>selfLink</code>' attribute. * * A link back to this permission. * * @param[in] value The new value. */ void set_self_link(const StringPiece& value) { *MutableStorage("selfLink") = value.data(); } /** * Determine if the '<code>teamDrivePermissionDetails</code>' attribute was * set. * * @return true if the '<code>teamDrivePermissionDetails</code>' attribute was * set. */ bool has_team_drive_permission_details() const { return Storage().isMember("teamDrivePermissionDetails"); } /** * Clears the '<code>teamDrivePermissionDetails</code>' attribute. */ void clear_team_drive_permission_details() { MutableStorage()->removeMember("teamDrivePermissionDetails"); } /** * Get a reference to the value of the * '<code>teamDrivePermissionDetails</code>' attribute. */ const client::JsonCppArray<PermissionTeamDrivePermissionDetails > get_team_drive_permission_details() const { const Json::Value& storage = Storage("teamDrivePermissionDetails"); return client::JsonValueToCppValueHelper<client::JsonCppArray<PermissionTeamDrivePermissionDetails > >(storage); } /** * Gets a reference to a mutable value of the * '<code>teamDrivePermissionDetails</code>' property. * * Details of whether the permissions on this Team Drive item are inherited or * directly on this item. This is an output-only field which is present only * for Team Drive items. * * @return The result can be modified to change the attribute value. */ client::JsonCppArray<PermissionTeamDrivePermissionDetails > mutable_teamDrivePermissionDetails() { Json::Value* storage = MutableStorage("teamDrivePermissionDetails"); return client::JsonValueToMutableCppValueHelper<client::JsonCppArray<PermissionTeamDrivePermissionDetails > >(storage); } /** * Determine if the '<code>type</code>' attribute was set. * * @return true if the '<code>type</code>' attribute was set. */ bool has_type() const { return Storage().isMember("type"); } /** * Clears the '<code>type</code>' attribute. */ void clear_type() { MutableStorage()->removeMember("type"); } /** * Get the value of the '<code>type</code>' attribute. */ const StringPiece get_type() const { const Json::Value& v = Storage("type"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>type</code>' attribute. * * The account type. Allowed values are: * - user * - group * - domain * - anyone. * * @param[in] value The new value. */ void set_type(const StringPiece& value) { *MutableStorage("type") = value.data(); } /** * Determine if the '<code>value</code>' attribute was set. * * @return true if the '<code>value</code>' attribute was set. */ bool has_value() const { return Storage().isMember("value"); } /** * Clears the '<code>value</code>' attribute. */ void clear_value() { MutableStorage()->removeMember("value"); } /** * Get the value of the '<code>value</code>' attribute. */ const StringPiece get_value() const { const Json::Value& v = Storage("value"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>value</code>' attribute. * * The email address or domain name for the entity. This is used during * inserts and is not populated in responses. When making a * drive.permissions.insert request, exactly one of the id or value fields * must be specified unless the permission type is anyone, in which case both * id and value are ignored. * * @param[in] value The new value. */ void set_value(const StringPiece& value) { *MutableStorage("value") = value.data(); } /** * Determine if the '<code>withLink</code>' attribute was set. * * @return true if the '<code>withLink</code>' attribute was set. */ bool has_with_link() const { return Storage().isMember("withLink"); } /** * Clears the '<code>withLink</code>' attribute. */ void clear_with_link() { MutableStorage()->removeMember("withLink"); } /** * Get the value of the '<code>withLink</code>' attribute. */ bool get_with_link() const { const Json::Value& storage = Storage("withLink"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>withLink</code>' attribute. * * Whether the link is required for this permission. * * @param[in] value The new value. */ void set_with_link(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("withLink")); } private: void operator=(const Permission&); }; // Permission } // namespace google_drive_api #endif // GOOGLE_DRIVE_API_PERMISSION_H_ <file_sep>/service_apis/youtube/google/youtube_api/video_age_gating.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_VIDEO_AGE_GATING_H_ #define GOOGLE_YOUTUBE_API_VIDEO_AGE_GATING_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * No description provided. * * @ingroup DataObject */ class VideoAgeGating : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static VideoAgeGating* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoAgeGating(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoAgeGating(Json::Value* storage); /** * Standard destructor. */ virtual ~VideoAgeGating(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::VideoAgeGating</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::VideoAgeGating"); } /** * Determine if the '<code>alcoholContent</code>' attribute was set. * * @return true if the '<code>alcoholContent</code>' attribute was set. */ bool has_alcohol_content() const { return Storage().isMember("alcoholContent"); } /** * Clears the '<code>alcoholContent</code>' attribute. */ void clear_alcohol_content() { MutableStorage()->removeMember("alcoholContent"); } /** * Get the value of the '<code>alcoholContent</code>' attribute. */ bool get_alcohol_content() const { const Json::Value& storage = Storage("alcoholContent"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>alcoholContent</code>' attribute. * * Indicates whether or not the video has alcoholic beverage content. Only * users of legal purchasing age in a particular country, as identified by * ICAP, can view the content. * * @param[in] value The new value. */ void set_alcohol_content(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("alcoholContent")); } /** * Determine if the '<code>restricted</code>' attribute was set. * * @return true if the '<code>restricted</code>' attribute was set. */ bool has_restricted() const { return Storage().isMember("restricted"); } /** * Clears the '<code>restricted</code>' attribute. */ void clear_restricted() { MutableStorage()->removeMember("restricted"); } /** * Get the value of the '<code>restricted</code>' attribute. */ bool get_restricted() const { const Json::Value& storage = Storage("restricted"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>restricted</code>' attribute. * * Age-restricted trailers. For redband trailers and adult-rated video-games. * Only users aged 18+ can view the content. The the field is true the content * is restricted to viewers aged 18+. Otherwise The field won't be present. * * @param[in] value The new value. */ void set_restricted(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("restricted")); } /** * Determine if the '<code>videoGameRating</code>' attribute was set. * * @return true if the '<code>videoGameRating</code>' attribute was set. */ bool has_video_game_rating() const { return Storage().isMember("videoGameRating"); } /** * Clears the '<code>videoGameRating</code>' attribute. */ void clear_video_game_rating() { MutableStorage()->removeMember("videoGameRating"); } /** * Get the value of the '<code>videoGameRating</code>' attribute. */ const StringPiece get_video_game_rating() const { const Json::Value& v = Storage("videoGameRating"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>videoGameRating</code>' attribute. * * Video game rating, if any. * * @param[in] value The new value. */ void set_video_game_rating(const StringPiece& value) { *MutableStorage("videoGameRating") = value.data(); } private: void operator=(const VideoAgeGating&); }; // VideoAgeGating } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_VIDEO_AGE_GATING_H_ <file_sep>/src/samples/youtube_broadcast_main.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ /* * Demo of inserting a broadcast and a stream then binding them together * using the YouTube Live API (V3) with OAuth2 for authorization. * * To run this sample you must have a Google APIs Project that enables * YouTube Data API using the cloud console as described in the * "Getting Started" document at * http://google.github.io/google-api-cpp-client/latest/start/get_started.html * * Run the sample with the command line * --client_secrets_path=<path> * where <path> is the path to the Client Secrets file you downloaded for * your project. Be sure the file has only user read-only permissions to * satisfy the security checks. * * Type the command "help" for a list of available commands in this sample. */ #include <string> using std::string; #include "samples/command_processor.h" #include "samples/installed_application.h" #include "googleapis/client/transport/curl_http_transport.h" #include "googleapis/client/transport/http_request.h" #include "googleapis/client/transport/http_response.h" #include "googleapis/client/transport/http_transport.h" #include "googleapis/client/util/date_time.h" #include "googleapis/client/util/status.h" #include <gflags/gflags.h> #include "googleapis/strings/numbers.h" #include "googleapis/strings/strcat.h" #include "googleapis/util/status.h" #include "google/youtube_api/youtube_api.h" namespace googleapis { // Small number to make paging easier to demonstrate. DEFINE_int32(max_results, 5, "Max results per page"); DEFINE_string(client_secrets_path, "", "REQUIRED: Path to JSON client_secrets file for OAuth."); using std::cerr; using std::cout; using std::endl; using client::JsonCppArray; using client::DateTime; using sample::InstalledServiceApplication; using google_youtube_api::CdnSettings; using google_youtube_api::LiveBroadcast; using google_youtube_api::LiveBroadcastContentDetails; using google_youtube_api::LiveBroadcastSnippet; using google_youtube_api::LiveBroadcastStatus; using google_youtube_api::LiveBroadcastsResource_BindMethod; using google_youtube_api::LiveBroadcastsResource_DeleteMethod; using google_youtube_api::LiveBroadcastsResource_InsertMethod; using google_youtube_api::LiveBroadcastsResource_ListMethodPager; using google_youtube_api::LiveStream; using google_youtube_api::LiveStreamSnippet; using google_youtube_api::LiveStreamStatus; using google_youtube_api::LiveStreamsResource_DeleteMethod; using google_youtube_api::LiveStreamsResource_InsertMethod; using google_youtube_api::LiveStreamsResource_ListMethodPager; using google_youtube_api::YouTubeService; static void DumpLiveBroadcastList(const JsonCppArray<LiveBroadcast>& list) { for (JsonCppArray<LiveBroadcast>::const_iterator it = list.begin(); it != list.end(); ++it) { const LiveBroadcast& bcast = *it; const LiveBroadcastSnippet& snippet = bcast.get_snippet(); const LiveBroadcastContentDetails& details = bcast.get_content_details(); string bound_id = details.has_bound_stream_id() ? details.get_bound_stream_id().as_string() : "<No Bound Stream>"; cout << " ID=" << bcast.get_id() << "\n" << " StreamID=" << bound_id << "\n" << " Start=" << snippet.get_scheduled_start_time().ToString() << "\n" << " Title=" << snippet.get_title() << endl; } } static void DumpLiveStreamList(const JsonCppArray<LiveStream>& list) { for (JsonCppArray<LiveStream>::const_iterator it = list.begin(); it != list.end(); ++it) { const LiveStream& stream = *it; string format = stream.has_cdn() ? stream.get_cdn().get_format().as_string() : "<No CDN available>"; cout << " ID=" << stream.get_id() << "\n" << " Format=" << format << "\n" << " ChannelID=" << stream.get_snippet().get_channel_id() << "\n" << " Title=" << stream.get_snippet().get_title() << endl; } } /* * Configures and manages YouTubeService instance and OAuth2.0 flow we'll use. * * The actual functionality for the sample is in the command processor. * * @see YouTubeBroadcastCommandProcessor */ class YouTubeBroadcastSampleApplication : public InstalledServiceApplication<YouTubeService> { public: YouTubeBroadcastSampleApplication() : InstalledServiceApplication<YouTubeService>("YouTubeBroadcastSample") { std::vector<string>* scopes = mutable_default_oauth2_scopes(); scopes->push_back(YouTubeService::SCOPES::YOUTUBE); scopes->push_back(YouTubeService::SCOPES::YOUTUBE_READONLY); } private: DISALLOW_COPY_AND_ASSIGN(YouTubeBroadcastSampleApplication); }; /* * Implements the commands available for this sample. */ class YouTubeBroadcastCommandProcessor : public sample::CommandProcessor { public: explicit YouTubeBroadcastCommandProcessor( YouTubeBroadcastSampleApplication* app) : app_(app) {} virtual ~YouTubeBroadcastCommandProcessor() {} virtual void Init() { AddBuiltinCommands(); AddCommand("authorize", new CommandEntry( "user_name [refresh token]", "Re-authorize user [with refresh token].\n" "The user_name is only used for persisting the credentials.\n" "The credentials will be persisted under the directory " "$HOME/.googleapis/user_name.\n" "If refresh token is empty then authorize interactively.", NewPermanentCallback( this, &YouTubeBroadcastCommandProcessor::AuthorizeHandler))); AddCommand( "revoke", new CommandEntry( "", "Revoke authorization. You will need to reauthorize again.\n", NewPermanentCallback( this, &YouTubeBroadcastCommandProcessor::RevokeHandler))); AddCommand( "create", new CommandEntry( "<start date> <minutes> <title>", "Create a new broadcast.", NewPermanentCallback( this, &YouTubeBroadcastCommandProcessor::CreateBroadcastHandler))); AddCommand( "delete", new CommandEntry( "<broadcast|stream> <ID>", "Deletes the live [broadcast or stream] resource with given ID.", NewPermanentCallback( this, &YouTubeBroadcastCommandProcessor::DeleteLiveHandler))); AddCommand( "broadcasts", new CommandEntry( "", "List your broadcasts. Can page through using 'next'.", NewPermanentCallback( this, &YouTubeBroadcastCommandProcessor::ListBroadcastsHandler))); AddCommand( "streams", new CommandEntry( "", "List your Streams. Can page through using 'next'.", NewPermanentCallback( this, &YouTubeBroadcastCommandProcessor::ListStreamsHandler))); AddCommand( "next", new CommandEntry( "", "List the next page since the previous 'list' or 'next'.", NewPermanentCallback( this, &YouTubeBroadcastCommandProcessor::NextBroadcastsHandler))); } private: void AuthorizeHandler(const string& cmd, const std::vector<string>& args) { if (args.size() == 0 || args.size() > 2) { cout << "no user_name provided." << endl; return; } googleapis::util::Status status = app_->ChangeUser(args[0]); if (status.ok()) { status = app_->AuthorizeClient(); } if (status.ok()) { cout << "Authorized as user '" << args[0] << "'" << endl; } else { cerr << status.ToString(); } } /* * Implements "revoke" command. * * Apps dont typically do this and rely on Google's User Consoles and * Dashboards to allow users to revoke permissions across applications. * However it is convienent, especially here, to allow the app to revoke * its permissions. */ void RevokeHandler(const string&, const std::vector<string>&) { app_->RevokeClient().IgnoreError(); } /* * Implements the "create" command. */ void CreateBroadcastHandler( const string& cmd, const std::vector<string>& args) { if (args.size() != 3) { cout << "Expected <start time> <minutes> <title>." << endl; return; } DateTime start_time(args[0]); if (!start_time.is_valid()) { cout << "Expected start time in format <YYYY-MM-DD>T<HH:MM:SS>Z" << endl; return; } int32 mins; if (!safe_strto32(args[1].c_str(), &mins)) { cout << "<minutes> was not a number." << endl; return; } DateTime end_time(start_time.ToEpochTime() + mins * 60); const string& title = args[2]; std::unique_ptr<LiveBroadcast> broadcast(LiveBroadcast::New()); LiveBroadcastSnippet broadcast_snippet = broadcast->mutable_snippet(); broadcast_snippet.set_title(title); broadcast_snippet.set_scheduled_start_time(start_time); broadcast_snippet.set_scheduled_end_time(end_time); LiveBroadcastStatus broadcast_status = broadcast->mutable_status(); broadcast_status.set_privacy_status("private"); string broadcast_parts = "snippet,status"; std::unique_ptr<LiveBroadcastsResource_InsertMethod> insert_broadcast( app_->service()->get_live_broadcasts().NewInsertMethod( app_->credential(), broadcast_parts, *broadcast.get())); std::unique_ptr<LiveBroadcast> got_broadcast(LiveBroadcast::New()); insert_broadcast->ExecuteAndParseResponse( got_broadcast.get()).IgnoreError(); if (!CheckAndLogResponse(insert_broadcast->http_response())) { return; } cout << "Inserted LiveBroadcast ID=" << got_broadcast->get_id() << endl; std::unique_ptr<LiveStream> stream(LiveStream::New()); LiveStreamSnippet stream_snippet = stream->mutable_snippet(); stream_snippet.set_title(string("Stream for ")+title); CdnSettings stream_cdn = stream->mutable_cdn(); stream_cdn.set_format("1080p"); stream_cdn.set_ingestion_type("rtmp"); string stream_parts = "snippet,cdn"; std::unique_ptr<LiveStreamsResource_InsertMethod> insert_stream( app_->service()->get_live_streams().NewInsertMethod( app_->credential(), stream_parts, *stream.get())); std::unique_ptr<LiveStream> got_stream(LiveStream::New()); insert_stream->ExecuteAndParseResponse(got_stream.get()).IgnoreError(); if (!CheckAndLogResponse(insert_stream->http_response())) { return; } cout << "Inserted LiveStream id=" << got_stream->get_id() << endl; std::unique_ptr<LiveBroadcastsResource_BindMethod> bind( app_->service()->get_live_broadcasts().NewBindMethod( app_->credential(), got_broadcast->get_id(), "id,contentDetails")); bind->set_stream_id(got_stream->get_id().as_string()); std::unique_ptr<LiveBroadcast> bound_broadcast(LiveBroadcast::New()); bind->ExecuteAndParseResponse(bound_broadcast.get()).IgnoreError(); if (!CheckAndLogResponse(bind->http_response())) { return; } cout << "Bound Broadcast is:\n" << *bound_broadcast.get() << endl; } /* * Implements the "delete" command. */ void DeleteLiveHandler( const string& cmd, const std::vector<string>& args) { if (args.size() != 2) { cout << "Expected <broadcast|stream> <ID>." << endl; return; } if (args[0] == "broadcast") { DeleteLiveBroadcastHandler(cmd, args); } else if (args[0] == "stream") { DeleteLiveStreamHandler(cmd, args); } else { cout << "Expected <broadcast|stream> <ID>." << endl; } } /* * Implements the "broadcasts" command. * * @see NextBroadcastsHandler */ void ListBroadcastsHandler(const string&, const std::vector<string>&) { streams_pager_.reset(NULL); const YouTubeService::LiveBroadcastsResource& rsrc = app_->service()->get_live_broadcasts(); // We could use a LiveBroadcastsResource_ListMethod but we'll instead use // a pager so that we can play with it. Reset the old one (if any). // The 'next' command will advance the pager. const string& parts = "id,snippet"; broadcasts_pager_.reset(rsrc.NewListMethodPager(app_->credential(), parts)); broadcasts_pager_->request()->set_max_results(FLAGS_max_results); broadcasts_pager_->request()->set_broadcast_status("all"); cout << "Getting (partial) broadcast list..." << endl; bool ok = broadcasts_pager_->NextPage(); CheckAndLogResponse(broadcasts_pager_->http_response()); if (ok) { DumpLiveBroadcastList(broadcasts_pager_->data()->get_items()); } if (broadcasts_pager_->is_done()) { cout << "There are no more results to page through." << endl; } else { cout << "\nEnter 'next' to see the next page of results." << endl; } } /* * Implements the "streams" command. * * @see NextStreamsHandler */ void ListStreamsHandler(const string&, const std::vector<string>&) { broadcasts_pager_.reset(NULL); const YouTubeService::LiveStreamsResource& rsrc = app_->service()->get_live_streams(); // We could use a LiveStreamsResource_ListMethod but we'll instead use // a pager so that we can play with it. Reset the old one (if any). // The 'next' command will advance the pager. const string& parts = "id,snippet"; streams_pager_.reset(rsrc.NewListMethodPager(app_->credential(), parts)); streams_pager_->request()->set_max_results(FLAGS_max_results); streams_pager_->request()->set_mine(true); // list only my streams. cout << "Getting (partial) stream list..." << endl; bool ok = streams_pager_->NextPage(); CheckAndLogResponse(streams_pager_->http_response()); if (ok) { DumpLiveStreamList(streams_pager_->data()->get_items()); } if (streams_pager_->is_done()) { cout << "There are no more results to page through." << endl; } else { cout << "\nEnter 'next' to see the next page of results." << endl; } } /* * Implements the "next" command. */ void NextHandler(const string& cmd, const std::vector<string>& args) { if (broadcasts_pager_.get()) { NextBroadcastsHandler(cmd, args); } else if (streams_pager_.get()) { NextStreamsHandler(cmd, args); } else { cout << "You must ask for 'broadcasts' or 'streams' first."; } } /* * Implements the "next" command for listing broadcasts. * * @see ListBroadcastsHandler */ void NextBroadcastsHandler(const string&, const std::vector<string>&) { CHECK(broadcasts_pager_.get()); cout << "Getting next page of broadcast list..." << endl; bool ok = broadcasts_pager_->NextPage(); CheckAndLogResponse(broadcasts_pager_->http_response()); if (ok) { DumpLiveBroadcastList(broadcasts_pager_->data()->get_items()); } if (broadcasts_pager_->is_done()) { cout << "There are no more results to page through." << endl; } else { cout << "\nEnter 'next' to see the next page of results." << endl; } } /* * Implements the "next" command for listing streams. * * @see ListStreamsHandler */ void NextStreamsHandler(const string&, const std::vector<string>&) { CHECK(streams_pager_.get()); cout << "Getting next page of streams list..." << endl; bool ok = streams_pager_->NextPage(); CheckAndLogResponse(streams_pager_->http_response()); if (ok) { DumpLiveStreamList(streams_pager_->data()->get_items()); } if (streams_pager_->is_done()) { cout << "There are no more results to page through." << endl; } else { cout << "\nEnter 'next' to see the next page of results." << endl; } } void DeleteLiveBroadcastHandler( const string&, const std::vector<string>& args) { string id(args[1]); std::unique_ptr<LiveBroadcastsResource_DeleteMethod> delete_broadcast( app_->service()->get_live_broadcasts().NewDeleteMethod( app_->credential(), id)); delete_broadcast->Execute().IgnoreError(); if (!CheckAndLogResponse(delete_broadcast->http_response())) { return; } cout << "Deleted LiveBroadcast ID=" << id << endl; } void DeleteLiveStreamHandler( const string&, const std::vector<string>& args) { string id(args[1]); std::unique_ptr<LiveStreamsResource_DeleteMethod> delete_broadcast( app_->service()->get_live_streams().NewDeleteMethod( app_->credential(), id)); delete_broadcast->Execute().IgnoreError(); if (!CheckAndLogResponse(delete_broadcast->http_response())) { return; } cout << "Deleted LiveStream ID=" << id << endl; } // At most one of these will not be NULL indicating which thing we // are listing so that we can have the command "next" apply to either // without being ambiguous. When we list "streams" or "broadcasts" it will // instantiate the pager we want and NULL the other one out. std::unique_ptr<LiveBroadcastsResource_ListMethodPager> broadcasts_pager_; std::unique_ptr<LiveStreamsResource_ListMethodPager> streams_pager_; YouTubeBroadcastSampleApplication* app_; DISALLOW_COPY_AND_ASSIGN(YouTubeBroadcastCommandProcessor); }; } // namespace googleapis using namespace googleapis; int main(int argc, char** argv) { YouTubeBroadcastSampleApplication app; googleapis::util::Status status = app.Init(FLAGS_client_secrets_path); if (!status.ok()) { cerr << "Could not initialize application." << endl; cerr << status.error_message() << endl; return -1; } YouTubeBroadcastCommandProcessor processor(&app); processor.Init(); processor.set_log_success_bodies(true); processor.RunShell(); return 0; } <file_sep>/service_apis/youtube/google/youtube_api/image_settings.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_IMAGE_SETTINGS_H_ #define GOOGLE_YOUTUBE_API_IMAGE_SETTINGS_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/localized_property.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Branding properties for images associated with the channel. * * @ingroup DataObject */ class ImageSettings : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static ImageSettings* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ImageSettings(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit ImageSettings(Json::Value* storage); /** * Standard destructor. */ virtual ~ImageSettings(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::ImageSettings</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::ImageSettings"); } /** * Determine if the '<code>backgroundImageUrl</code>' attribute was set. * * @return true if the '<code>backgroundImageUrl</code>' attribute was set. */ bool has_background_image_url() const { return Storage().isMember("backgroundImageUrl"); } /** * Clears the '<code>backgroundImageUrl</code>' attribute. */ void clear_background_image_url() { MutableStorage()->removeMember("backgroundImageUrl"); } /** * Get a reference to the value of the '<code>backgroundImageUrl</code>' * attribute. */ const LocalizedProperty get_background_image_url() const; /** * Gets a reference to a mutable value of the * '<code>backgroundImageUrl</code>' property. * * The URL for the background image shown on the video watch page. The image * should be 1200px by 615px, with a maximum file size of 128k. * * @return The result can be modified to change the attribute value. */ LocalizedProperty mutable_backgroundImageUrl(); /** * Determine if the '<code>bannerExternalUrl</code>' attribute was set. * * @return true if the '<code>bannerExternalUrl</code>' attribute was set. */ bool has_banner_external_url() const { return Storage().isMember("bannerExternalUrl"); } /** * Clears the '<code>bannerExternalUrl</code>' attribute. */ void clear_banner_external_url() { MutableStorage()->removeMember("bannerExternalUrl"); } /** * Get the value of the '<code>bannerExternalUrl</code>' attribute. */ const StringPiece get_banner_external_url() const { const Json::Value& v = Storage("bannerExternalUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bannerExternalUrl</code>' attribute. * * This is used only in update requests; if it's set, we use this URL to * generate all of the above banner URLs. * * @param[in] value The new value. */ void set_banner_external_url(const StringPiece& value) { *MutableStorage("bannerExternalUrl") = value.data(); } /** * Determine if the '<code>bannerImageUrl</code>' attribute was set. * * @return true if the '<code>bannerImageUrl</code>' attribute was set. */ bool has_banner_image_url() const { return Storage().isMember("bannerImageUrl"); } /** * Clears the '<code>bannerImageUrl</code>' attribute. */ void clear_banner_image_url() { MutableStorage()->removeMember("bannerImageUrl"); } /** * Get the value of the '<code>bannerImageUrl</code>' attribute. */ const StringPiece get_banner_image_url() const { const Json::Value& v = Storage("bannerImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bannerImageUrl</code>' attribute. * * Banner image. Desktop size (1060x175). * * @param[in] value The new value. */ void set_banner_image_url(const StringPiece& value) { *MutableStorage("bannerImageUrl") = value.data(); } /** * Determine if the '<code>bannerMobileExtraHdImageUrl</code>' attribute was * set. * * @return true if the '<code>bannerMobileExtraHdImageUrl</code>' attribute * was set. */ bool has_banner_mobile_extra_hd_image_url() const { return Storage().isMember("bannerMobileExtraHdImageUrl"); } /** * Clears the '<code>bannerMobileExtraHdImageUrl</code>' attribute. */ void clear_banner_mobile_extra_hd_image_url() { MutableStorage()->removeMember("bannerMobileExtraHdImageUrl"); } /** * Get the value of the '<code>bannerMobileExtraHdImageUrl</code>' attribute. */ const StringPiece get_banner_mobile_extra_hd_image_url() const { const Json::Value& v = Storage("bannerMobileExtraHdImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bannerMobileExtraHdImageUrl</code>' attribute. * * Banner image. Mobile size high resolution (1440x395). * * @param[in] value The new value. */ void set_banner_mobile_extra_hd_image_url(const StringPiece& value) { *MutableStorage("bannerMobileExtraHdImageUrl") = value.data(); } /** * Determine if the '<code>bannerMobileHdImageUrl</code>' attribute was set. * * @return true if the '<code>bannerMobileHdImageUrl</code>' attribute was * set. */ bool has_banner_mobile_hd_image_url() const { return Storage().isMember("bannerMobileHdImageUrl"); } /** * Clears the '<code>bannerMobileHdImageUrl</code>' attribute. */ void clear_banner_mobile_hd_image_url() { MutableStorage()->removeMember("bannerMobileHdImageUrl"); } /** * Get the value of the '<code>bannerMobileHdImageUrl</code>' attribute. */ const StringPiece get_banner_mobile_hd_image_url() const { const Json::Value& v = Storage("bannerMobileHdImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bannerMobileHdImageUrl</code>' attribute. * * Banner image. Mobile size high resolution (1280x360). * * @param[in] value The new value. */ void set_banner_mobile_hd_image_url(const StringPiece& value) { *MutableStorage("bannerMobileHdImageUrl") = value.data(); } /** * Determine if the '<code>bannerMobileImageUrl</code>' attribute was set. * * @return true if the '<code>bannerMobileImageUrl</code>' attribute was set. */ bool has_banner_mobile_image_url() const { return Storage().isMember("bannerMobileImageUrl"); } /** * Clears the '<code>bannerMobileImageUrl</code>' attribute. */ void clear_banner_mobile_image_url() { MutableStorage()->removeMember("bannerMobileImageUrl"); } /** * Get the value of the '<code>bannerMobileImageUrl</code>' attribute. */ const StringPiece get_banner_mobile_image_url() const { const Json::Value& v = Storage("bannerMobileImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bannerMobileImageUrl</code>' attribute. * * Banner image. Mobile size (640x175). * * @param[in] value The new value. */ void set_banner_mobile_image_url(const StringPiece& value) { *MutableStorage("bannerMobileImageUrl") = value.data(); } /** * Determine if the '<code>bannerMobileLowImageUrl</code>' attribute was set. * * @return true if the '<code>bannerMobileLowImageUrl</code>' attribute was * set. */ bool has_banner_mobile_low_image_url() const { return Storage().isMember("bannerMobileLowImageUrl"); } /** * Clears the '<code>bannerMobileLowImageUrl</code>' attribute. */ void clear_banner_mobile_low_image_url() { MutableStorage()->removeMember("bannerMobileLowImageUrl"); } /** * Get the value of the '<code>bannerMobileLowImageUrl</code>' attribute. */ const StringPiece get_banner_mobile_low_image_url() const { const Json::Value& v = Storage("bannerMobileLowImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bannerMobileLowImageUrl</code>' attribute. * * Banner image. Mobile size low resolution (320x88). * * @param[in] value The new value. */ void set_banner_mobile_low_image_url(const StringPiece& value) { *MutableStorage("bannerMobileLowImageUrl") = value.data(); } /** * Determine if the '<code>bannerMobileMediumHdImageUrl</code>' attribute was * set. * * @return true if the '<code>bannerMobileMediumHdImageUrl</code>' attribute * was set. */ bool has_banner_mobile_medium_hd_image_url() const { return Storage().isMember("bannerMobileMediumHdImageUrl"); } /** * Clears the '<code>bannerMobileMediumHdImageUrl</code>' attribute. */ void clear_banner_mobile_medium_hd_image_url() { MutableStorage()->removeMember("bannerMobileMediumHdImageUrl"); } /** * Get the value of the '<code>bannerMobileMediumHdImageUrl</code>' attribute. */ const StringPiece get_banner_mobile_medium_hd_image_url() const { const Json::Value& v = Storage("bannerMobileMediumHdImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bannerMobileMediumHdImageUrl</code>' attribute. * * Banner image. Mobile size medium/high resolution (960x263). * * @param[in] value The new value. */ void set_banner_mobile_medium_hd_image_url(const StringPiece& value) { *MutableStorage("bannerMobileMediumHdImageUrl") = value.data(); } /** * Determine if the '<code>bannerTabletExtraHdImageUrl</code>' attribute was * set. * * @return true if the '<code>bannerTabletExtraHdImageUrl</code>' attribute * was set. */ bool has_banner_tablet_extra_hd_image_url() const { return Storage().isMember("bannerTabletExtraHdImageUrl"); } /** * Clears the '<code>bannerTabletExtraHdImageUrl</code>' attribute. */ void clear_banner_tablet_extra_hd_image_url() { MutableStorage()->removeMember("bannerTabletExtraHdImageUrl"); } /** * Get the value of the '<code>bannerTabletExtraHdImageUrl</code>' attribute. */ const StringPiece get_banner_tablet_extra_hd_image_url() const { const Json::Value& v = Storage("bannerTabletExtraHdImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bannerTabletExtraHdImageUrl</code>' attribute. * * Banner image. Tablet size extra high resolution (2560x424). * * @param[in] value The new value. */ void set_banner_tablet_extra_hd_image_url(const StringPiece& value) { *MutableStorage("bannerTabletExtraHdImageUrl") = value.data(); } /** * Determine if the '<code>bannerTabletHdImageUrl</code>' attribute was set. * * @return true if the '<code>bannerTabletHdImageUrl</code>' attribute was * set. */ bool has_banner_tablet_hd_image_url() const { return Storage().isMember("bannerTabletHdImageUrl"); } /** * Clears the '<code>bannerTabletHdImageUrl</code>' attribute. */ void clear_banner_tablet_hd_image_url() { MutableStorage()->removeMember("bannerTabletHdImageUrl"); } /** * Get the value of the '<code>bannerTabletHdImageUrl</code>' attribute. */ const StringPiece get_banner_tablet_hd_image_url() const { const Json::Value& v = Storage("bannerTabletHdImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bannerTabletHdImageUrl</code>' attribute. * * Banner image. Tablet size high resolution (2276x377). * * @param[in] value The new value. */ void set_banner_tablet_hd_image_url(const StringPiece& value) { *MutableStorage("bannerTabletHdImageUrl") = value.data(); } /** * Determine if the '<code>bannerTabletImageUrl</code>' attribute was set. * * @return true if the '<code>bannerTabletImageUrl</code>' attribute was set. */ bool has_banner_tablet_image_url() const { return Storage().isMember("bannerTabletImageUrl"); } /** * Clears the '<code>bannerTabletImageUrl</code>' attribute. */ void clear_banner_tablet_image_url() { MutableStorage()->removeMember("bannerTabletImageUrl"); } /** * Get the value of the '<code>bannerTabletImageUrl</code>' attribute. */ const StringPiece get_banner_tablet_image_url() const { const Json::Value& v = Storage("bannerTabletImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bannerTabletImageUrl</code>' attribute. * * Banner image. Tablet size (1707x283). * * @param[in] value The new value. */ void set_banner_tablet_image_url(const StringPiece& value) { *MutableStorage("bannerTabletImageUrl") = value.data(); } /** * Determine if the '<code>bannerTabletLowImageUrl</code>' attribute was set. * * @return true if the '<code>bannerTabletLowImageUrl</code>' attribute was * set. */ bool has_banner_tablet_low_image_url() const { return Storage().isMember("bannerTabletLowImageUrl"); } /** * Clears the '<code>bannerTabletLowImageUrl</code>' attribute. */ void clear_banner_tablet_low_image_url() { MutableStorage()->removeMember("bannerTabletLowImageUrl"); } /** * Get the value of the '<code>bannerTabletLowImageUrl</code>' attribute. */ const StringPiece get_banner_tablet_low_image_url() const { const Json::Value& v = Storage("bannerTabletLowImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bannerTabletLowImageUrl</code>' attribute. * * Banner image. Tablet size low resolution (1138x188). * * @param[in] value The new value. */ void set_banner_tablet_low_image_url(const StringPiece& value) { *MutableStorage("bannerTabletLowImageUrl") = value.data(); } /** * Determine if the '<code>bannerTvHighImageUrl</code>' attribute was set. * * @return true if the '<code>bannerTvHighImageUrl</code>' attribute was set. */ bool has_banner_tv_high_image_url() const { return Storage().isMember("bannerTvHighImageUrl"); } /** * Clears the '<code>bannerTvHighImageUrl</code>' attribute. */ void clear_banner_tv_high_image_url() { MutableStorage()->removeMember("bannerTvHighImageUrl"); } /** * Get the value of the '<code>bannerTvHighImageUrl</code>' attribute. */ const StringPiece get_banner_tv_high_image_url() const { const Json::Value& v = Storage("bannerTvHighImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bannerTvHighImageUrl</code>' attribute. * * Banner image. TV size high resolution (1920x1080). * * @param[in] value The new value. */ void set_banner_tv_high_image_url(const StringPiece& value) { *MutableStorage("bannerTvHighImageUrl") = value.data(); } /** * Determine if the '<code>bannerTvImageUrl</code>' attribute was set. * * @return true if the '<code>bannerTvImageUrl</code>' attribute was set. */ bool has_banner_tv_image_url() const { return Storage().isMember("bannerTvImageUrl"); } /** * Clears the '<code>bannerTvImageUrl</code>' attribute. */ void clear_banner_tv_image_url() { MutableStorage()->removeMember("bannerTvImageUrl"); } /** * Get the value of the '<code>bannerTvImageUrl</code>' attribute. */ const StringPiece get_banner_tv_image_url() const { const Json::Value& v = Storage("bannerTvImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bannerTvImageUrl</code>' attribute. * * Banner image. TV size extra high resolution (2120x1192). * * @param[in] value The new value. */ void set_banner_tv_image_url(const StringPiece& value) { *MutableStorage("bannerTvImageUrl") = value.data(); } /** * Determine if the '<code>bannerTvLowImageUrl</code>' attribute was set. * * @return true if the '<code>bannerTvLowImageUrl</code>' attribute was set. */ bool has_banner_tv_low_image_url() const { return Storage().isMember("bannerTvLowImageUrl"); } /** * Clears the '<code>bannerTvLowImageUrl</code>' attribute. */ void clear_banner_tv_low_image_url() { MutableStorage()->removeMember("bannerTvLowImageUrl"); } /** * Get the value of the '<code>bannerTvLowImageUrl</code>' attribute. */ const StringPiece get_banner_tv_low_image_url() const { const Json::Value& v = Storage("bannerTvLowImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bannerTvLowImageUrl</code>' attribute. * * Banner image. TV size low resolution (854x480). * * @param[in] value The new value. */ void set_banner_tv_low_image_url(const StringPiece& value) { *MutableStorage("bannerTvLowImageUrl") = value.data(); } /** * Determine if the '<code>bannerTvMediumImageUrl</code>' attribute was set. * * @return true if the '<code>bannerTvMediumImageUrl</code>' attribute was * set. */ bool has_banner_tv_medium_image_url() const { return Storage().isMember("bannerTvMediumImageUrl"); } /** * Clears the '<code>bannerTvMediumImageUrl</code>' attribute. */ void clear_banner_tv_medium_image_url() { MutableStorage()->removeMember("bannerTvMediumImageUrl"); } /** * Get the value of the '<code>bannerTvMediumImageUrl</code>' attribute. */ const StringPiece get_banner_tv_medium_image_url() const { const Json::Value& v = Storage("bannerTvMediumImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>bannerTvMediumImageUrl</code>' attribute. * * Banner image. TV size medium resolution (1280x720). * * @param[in] value The new value. */ void set_banner_tv_medium_image_url(const StringPiece& value) { *MutableStorage("bannerTvMediumImageUrl") = value.data(); } /** * Determine if the '<code>largeBrandedBannerImageImapScript</code>' attribute * was set. * * @return true if the '<code>largeBrandedBannerImageImapScript</code>' * attribute was set. */ bool has_large_branded_banner_image_imap_script() const { return Storage().isMember("largeBrandedBannerImageImapScript"); } /** * Clears the '<code>largeBrandedBannerImageImapScript</code>' attribute. */ void clear_large_branded_banner_image_imap_script() { MutableStorage()->removeMember("largeBrandedBannerImageImapScript"); } /** * Get a reference to the value of the * '<code>largeBrandedBannerImageImapScript</code>' attribute. */ const LocalizedProperty get_large_branded_banner_image_imap_script() const; /** * Gets a reference to a mutable value of the * '<code>largeBrandedBannerImageImapScript</code>' property. * * The image map script for the large banner image. * * @return The result can be modified to change the attribute value. */ LocalizedProperty mutable_largeBrandedBannerImageImapScript(); /** * Determine if the '<code>largeBrandedBannerImageUrl</code>' attribute was * set. * * @return true if the '<code>largeBrandedBannerImageUrl</code>' attribute was * set. */ bool has_large_branded_banner_image_url() const { return Storage().isMember("largeBrandedBannerImageUrl"); } /** * Clears the '<code>largeBrandedBannerImageUrl</code>' attribute. */ void clear_large_branded_banner_image_url() { MutableStorage()->removeMember("largeBrandedBannerImageUrl"); } /** * Get a reference to the value of the * '<code>largeBrandedBannerImageUrl</code>' attribute. */ const LocalizedProperty get_large_branded_banner_image_url() const; /** * Gets a reference to a mutable value of the * '<code>largeBrandedBannerImageUrl</code>' property. * * The URL for the 854px by 70px image that appears below the video player in * the expanded video view of the video watch page. * * @return The result can be modified to change the attribute value. */ LocalizedProperty mutable_largeBrandedBannerImageUrl(); /** * Determine if the '<code>smallBrandedBannerImageImapScript</code>' attribute * was set. * * @return true if the '<code>smallBrandedBannerImageImapScript</code>' * attribute was set. */ bool has_small_branded_banner_image_imap_script() const { return Storage().isMember("smallBrandedBannerImageImapScript"); } /** * Clears the '<code>smallBrandedBannerImageImapScript</code>' attribute. */ void clear_small_branded_banner_image_imap_script() { MutableStorage()->removeMember("smallBrandedBannerImageImapScript"); } /** * Get a reference to the value of the * '<code>smallBrandedBannerImageImapScript</code>' attribute. */ const LocalizedProperty get_small_branded_banner_image_imap_script() const; /** * Gets a reference to a mutable value of the * '<code>smallBrandedBannerImageImapScript</code>' property. * * The image map script for the small banner image. * * @return The result can be modified to change the attribute value. */ LocalizedProperty mutable_smallBrandedBannerImageImapScript(); /** * Determine if the '<code>smallBrandedBannerImageUrl</code>' attribute was * set. * * @return true if the '<code>smallBrandedBannerImageUrl</code>' attribute was * set. */ bool has_small_branded_banner_image_url() const { return Storage().isMember("smallBrandedBannerImageUrl"); } /** * Clears the '<code>smallBrandedBannerImageUrl</code>' attribute. */ void clear_small_branded_banner_image_url() { MutableStorage()->removeMember("smallBrandedBannerImageUrl"); } /** * Get a reference to the value of the * '<code>smallBrandedBannerImageUrl</code>' attribute. */ const LocalizedProperty get_small_branded_banner_image_url() const; /** * Gets a reference to a mutable value of the * '<code>smallBrandedBannerImageUrl</code>' property. * * The URL for the 640px by 70px banner image that appears below the video * player in the default view of the video watch page. * * @return The result can be modified to change the attribute value. */ LocalizedProperty mutable_smallBrandedBannerImageUrl(); /** * Determine if the '<code>trackingImageUrl</code>' attribute was set. * * @return true if the '<code>trackingImageUrl</code>' attribute was set. */ bool has_tracking_image_url() const { return Storage().isMember("trackingImageUrl"); } /** * Clears the '<code>trackingImageUrl</code>' attribute. */ void clear_tracking_image_url() { MutableStorage()->removeMember("trackingImageUrl"); } /** * Get the value of the '<code>trackingImageUrl</code>' attribute. */ const StringPiece get_tracking_image_url() const { const Json::Value& v = Storage("trackingImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>trackingImageUrl</code>' attribute. * * The URL for a 1px by 1px tracking pixel that can be used to collect * statistics for views of the channel or video pages. * * @param[in] value The new value. */ void set_tracking_image_url(const StringPiece& value) { *MutableStorage("trackingImageUrl") = value.data(); } /** * Determine if the '<code>watchIconImageUrl</code>' attribute was set. * * @return true if the '<code>watchIconImageUrl</code>' attribute was set. */ bool has_watch_icon_image_url() const { return Storage().isMember("watchIconImageUrl"); } /** * Clears the '<code>watchIconImageUrl</code>' attribute. */ void clear_watch_icon_image_url() { MutableStorage()->removeMember("watchIconImageUrl"); } /** * Get the value of the '<code>watchIconImageUrl</code>' attribute. */ const StringPiece get_watch_icon_image_url() const { const Json::Value& v = Storage("watchIconImageUrl"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>watchIconImageUrl</code>' attribute. * * The URL for the image that appears above the top-left corner of the video * player. This is a 25-pixel-high image with a flexible width that cannot * exceed 170 pixels. * * @param[in] value The new value. */ void set_watch_icon_image_url(const StringPiece& value) { *MutableStorage("watchIconImageUrl") = value.data(); } private: void operator=(const ImageSettings&); }; // ImageSettings } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_IMAGE_SETTINGS_H_ <file_sep>/src/googleapis/client/auth/oauth2_service_authorization.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <memory> #include "googleapis/config.h" #include "googleapis/client/auth/jwt_builder.h" #include "googleapis/client/auth/oauth2_service_authorization.h" #include "googleapis/client/data/data_reader.h" #include "googleapis/client/transport/http_transport.h" #include "googleapis/client/transport/http_request.h" #include "googleapis/client/transport/http_response.h" #include "googleapis/client/util/date_time.h" #include "googleapis/client/util/file_utils.h" #include "googleapis/client/util/uri_utils.h" #include "googleapis/client/util/status.h" #include <glog/logging.h> #include "googleapis/strings/escaping.h" #include "googleapis/strings/strcat.h" #include "googleapis/util/file.h" #include <openssl/ossl_typ.h> #include <openssl/bio.h> #include <openssl/buffer.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/pkcs12.h> #include <openssl/sha.h> #include <openssl/x509.h> namespace googleapis { namespace client { OAuth2ServiceAccountFlow::OAuth2ServiceAccountFlow( HttpTransport* transport) : OAuth2AuthorizationFlow(transport) { } OAuth2ServiceAccountFlow::~OAuth2ServiceAccountFlow() { } void OAuth2ServiceAccountFlow::set_private_key(const string& key) { DCHECK(p12_path_.empty()); private_key_ = key; } util::Status OAuth2ServiceAccountFlow::SetPrivateKeyPkcs12Path( const string& path) { DCHECK(private_key_.empty()); p12_path_.clear(); googleapis::util::Status status = SensitiveFileUtils::VerifyIsSecureFile(path, false); if (!status.ok()) return status; p12_path_ = path; return StatusOk(); } util::Status OAuth2ServiceAccountFlow::InitFromJsonData( const SimpleJsonData* data) { googleapis::util::Status status = OAuth2AuthorizationFlow::InitFromJsonData(data); if (!status.ok()) return status; if (!GetStringAttribute(data, "client_email", &client_email_)) { return StatusInvalidArgument(StrCat("Missing client_email attribute")); } return StatusOk(); } util::Status OAuth2ServiceAccountFlow::PerformRefreshToken( const OAuth2RequestOptions& options, OAuth2Credential* credential) { string claims = MakeJwtClaims(options); string jwt; googleapis::util::Status status = MakeJwt(claims, &jwt); if (!status.ok()) return status; string grant_type = "urn:ietf:params:oauth:grant-type:jwt-bearer"; string content = StrCat("grant_type=", EscapeForUrl(grant_type), "&assertion=", jwt); std::unique_ptr<HttpRequest> request( transport()->NewHttpRequest(HttpRequest::POST)); if (options.timeout_ms > 0) { request->mutable_options()->set_timeout_ms(options.timeout_ms); } request->set_url(client_spec().token_uri()); request->set_content_type(HttpRequest::ContentType_FORM_URL_ENCODED); request->set_content_reader(NewUnmanagedInMemoryDataReader(content)); status = request->Execute(); if (status.ok()) { status = credential->Update(request->response()->body_reader()); } else { VLOG(1) << "Failed to update credential"; } return status; } string OAuth2ServiceAccountFlow::MakeJwtClaims( const OAuth2RequestOptions& options) const { time_t now = DateTime().ToEpochTime(); int duration_secs = 60 * 60; // 1 hour const string* scopes = &options.scopes; if (scopes->empty()) { scopes = &default_scopes(); if (scopes->empty()) { LOG(WARNING) << "Making claims without any scopes"; } } string claims = "{"; const string sep(","); if (!options.email.empty()) { AppendJsonStringAttribute(&claims, sep, "prn", options.email); } AppendJsonStringAttribute(&claims, "", "scope", *scopes); AppendJsonStringAttribute(&claims, sep, "iss", client_email_); AppendJsonStringAttribute(&claims, sep, "aud", client_spec().token_uri()); AppendJsonScalarAttribute(&claims, sep, "exp", now + duration_secs); AppendJsonScalarAttribute(&claims, sep, "iat", now); StrAppend(&claims, "}"); return claims; } util::Status OAuth2ServiceAccountFlow::ConstructSignedJwt( const string& plain_claims, string* result) const { return MakeJwt(plain_claims, result); } util::Status OAuth2ServiceAccountFlow::MakeJwt( const string& claims, string* jwt) const { EVP_PKEY* pkey = NULL; if (!p12_path_.empty()) { DCHECK(private_key_.empty()); VLOG(1) << "Loading private key from " << p12_path_; pkey = JwtBuilder::LoadPkeyFromP12Path(p12_path_.c_str()); } else if (!private_key_.empty()) { pkey = JwtBuilder::LoadPkeyFromData(private_key_); } else { return StatusInternalError("PrivateKey not set"); } if (!pkey) { return StatusInternalError("Could not load pkey"); } googleapis::util::Status status = JwtBuilder::MakeJwtUsingEvp(claims, pkey, jwt); EVP_PKEY_free(pkey); return status; } } // namespace client } // namespace googleapis <file_sep>/src/googleapis/client/transport/http_transport.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <map> #include "googleapis/client/data/data_reader.h" #include "googleapis/client/data/data_writer.h" #include "googleapis/util/executor.h" #include "googleapis/client/transport/ca_paths.h" #include "googleapis/client/transport/http_transport.h" #include "googleapis/client/transport/http_authorization.h" #include "googleapis/client/transport/http_request.h" #include "googleapis/client/transport/http_response.h" #include "googleapis/client/transport/http_scribe.h" #include "googleapis/client/transport/http_types.h" #include "googleapis/client/transport/versioninfo.h" #include "googleapis/client/util/status.h" #include "googleapis/client/util/program_path.h" #include <glog/logging.h> #include "googleapis/strings/strcat.h" #include "googleapis/strings/stringpiece.h" #include "googleapis/strings/strip.h" #include "googleapis/strings/numbers.h" #include "googleapis/strings/util.h" namespace googleapis { namespace { string BuildStandardUserAgentString(const string& application) { string user_agent; if (!application.empty()) { user_agent = StrCat(application, " "); } StrAppend(&user_agent, client::HttpTransportOptions::kGoogleApisUserAgent, "/", client::VersionInfo::GetVersionString(), " ", client::VersionInfo::GetPlatformString()); return user_agent; } } // anonymous namespace namespace client { // These global constants are declared in http_types.h const string kCRLF("\r\n"); // NOLINT const string kCRLFCRLF("\r\n\r\n"); // NOLINT HttpTransportLayerConfig::HttpTransportLayerConfig() { ResetDefaultErrorHandler(new HttpTransportErrorHandler); } HttpTransportLayerConfig::~HttpTransportLayerConfig() { } void HttpTransportLayerConfig::ResetDefaultErrorHandler( HttpTransportErrorHandler* error_handler) { VLOG(1) << "Resetting default error handler"; default_error_handler_.reset(error_handler); default_options_.set_error_handler(error_handler); } void HttpTransportLayerConfig::ResetDefaultExecutor( thread::Executor* executor) { VLOG(1) << "Resetting default executor"; default_executor_.reset(executor); default_options_.set_executor(executor); } void HttpTransportLayerConfig::ResetDefaultTransportFactory( HttpTransportFactory* factory) { VLOG(1) << "Setting default transport factory = " << factory->default_id(); default_transport_factory_.reset(factory); } void HttpTransportOptions::set_cacerts_path(const string& path) { VLOG(1) << "Initializing cacerts_path=" << path; cacerts_path_ = path; ssl_verification_disabled_ = path == kDisableSslVerification; if (ssl_verification_disabled_) LOG(WARNING) << "Disabled SSL verification"; } void HttpTransportOptions::set_connect_timeout_ms(int64 connect_timeout_ms) { VLOG(1) << "Initializing connect_timeout_ms=" << connect_timeout_ms; if (connect_timeout_ms < 0) { connect_timeout_ms = 0; } connect_timeout_ms_ = connect_timeout_ms; } void HttpTransportOptions::set_nonstandard_user_agent(const string& agent) { VLOG(1) << "Setting user_agent = " << agent; user_agent_ = agent; } void HttpTransportOptions::SetApplicationName(const string& name) { user_agent_ = BuildStandardUserAgentString(name); VLOG(1) << "Setting ApplicationName = " << name; } HttpTransportErrorHandler::HttpTransportErrorHandler() { } HttpTransportErrorHandler::~HttpTransportErrorHandler() { auto begin = specialized_http_code_handlers_.begin(); auto end = specialized_http_code_handlers_.end(); while (begin != end) { auto temp = begin; ++begin; delete temp->second; } } void HttpTransportErrorHandler::ResetHttpCodeHandler( int code, HttpTransportErrorHandler::HttpCodeHandler* handler) { std::map<int, HttpCodeHandler*>::iterator found = specialized_http_code_handlers_.find(code); if (found != specialized_http_code_handlers_.end()) { delete found->second; if (!handler) { specialized_http_code_handlers_.erase(found); } } if (handler) { specialized_http_code_handlers_.insert(std::make_pair(code, handler)); } } bool HttpTransportErrorHandler::HandleTransportError( int num_retries, HttpRequest* request) const { return false; } void HttpTransportErrorHandler::HandleTransportErrorAsync( int num_retries, HttpRequest* request, Callback1<bool>* callback) const { callback->Run(false); } bool HttpTransportErrorHandler::HandleHttpError( int num_retries_so_far, HttpRequest* request) const { int http_code = request->response()->http_code(); std::map<int, HttpCodeHandler*>::const_iterator found = specialized_http_code_handlers_.find(http_code); if (found != specialized_http_code_handlers_.end()) { VLOG(2) << "Using overriden error handler for http_code=" << http_code; return found->second->Run(num_retries_so_far, request); } if (http_code == HttpStatusCode::UNAUTHORIZED) { if (!num_retries_so_far) { // Only try unauthorized once. AuthorizationCredential* credential = request->credential(); if (credential) { googleapis::util::Status status = credential->Refresh(); if (status.ok()) { VLOG(2) << "Refreshed credential"; status = credential->AuthorizeRequest(request); if (status.ok()) { VLOG(1) << "Re-authorized credential"; return true; } else { LOG(ERROR) << "Failed reauthorizing request: " << status.error_message(); } } else { LOG(ERROR) << "Failed refreshing credential: " << status.error_message(); } } else { VLOG(2) << "No credential provided where one was expected."; } } else { // TODO(user): 20130616 // Here a retry is a retry. So a 503 retry that results in a 401 // would fail even though we never retried the 401 error. VLOG(2) << "Already retried with a http_code=" << HttpStatusCode::UNAUTHORIZED; } } else { // This isnt to say that the caller wont be handling the error later. VLOG(2) << "No configured error handler for http_code=" << http_code; } return false; } void HttpTransportErrorHandler::HandleHttpErrorAsync( int num_retries_so_far, HttpRequest* request, Callback1<bool>* callback) const { int http_code = request->response()->http_code(); std::map<int, HttpCodeHandler*>::const_iterator found = specialized_http_code_handlers_.find(http_code); if (found != specialized_http_code_handlers_.end()) { VLOG(2) << "Using overriden error handler for http_code=" << http_code; callback->Run(found->second->Run(num_retries_so_far, request)); return; } if (http_code == HttpStatusCode::UNAUTHORIZED) { if (!num_retries_so_far) { // Only try unauthorized once. AuthorizationCredential* credential = request->credential(); if (credential) { Callback1<util::Status>* cb = NewCallback(this, &HttpTransportErrorHandler::HandleRefreshAsync, callback, request); credential->RefreshAsync(cb); return; } else { VLOG(2) << "No credential provided where one was expected."; } } else { // TODO(user): 20130616 // Here a retry is a retry. So a 503 retry that results in a 401 // would fail even though we never retried the 401 error. VLOG(2) << "Already retried with a http_code=" << HttpStatusCode::UNAUTHORIZED; } } else { // This isnt to say that the caller wont be handling the error later. VLOG(2) << "No configured error handler for http_code=" << http_code; } callback->Run(false); } void HttpTransportErrorHandler::HandleRefreshAsync( Callback1<bool>* callback, HttpRequest* request, googleapis::util::Status status) const { if (status.ok()) { VLOG(2) << "Refreshed credential"; status = request->credential()->AuthorizeRequest(request); if (status.ok()) { VLOG(1) << "Re-authorized credential"; callback->Run(true); return; } else { LOG(ERROR) << "Failed reauthorizing request: " << status.error_message(); } } else { LOG(ERROR) << "Failed refreshing credential: " << status.error_message(); } callback->Run(false); } bool HttpTransportErrorHandler::HandleRedirect( int num_redirects, HttpRequest* request) const { return ShouldRetryRedirect_(num_redirects, request); } void HttpTransportErrorHandler::HandleRedirectAsync( int num_redirects, HttpRequest* request, Callback1<bool>* callback) const { callback->Run(ShouldRetryRedirect_(num_redirects, request)); } bool HttpTransportErrorHandler::ShouldRetryRedirect_( int num_redirects, HttpRequest* request) const { int http_code = request->response()->http_code(); std::map<int, HttpCodeHandler*>::const_iterator found = specialized_http_code_handlers_.find(http_code); if (found != specialized_http_code_handlers_.end()) { VLOG(2) << "Using overriden redirect handler for http_code=" << http_code; return found->second->Run(num_redirects, request); } if (HttpStatusCode::IsRedirect(http_code) && http_code != HttpStatusCode::MULTIPLE_CHOICES) { googleapis::util::Status status = request->PrepareRedirect(num_redirects); if (status.ok()) { return true; } request->mutable_state()->set_transport_status(status); } return false; } HttpTransportOptions::HttpTransportOptions() : proxy_port_(0), ssl_verification_disabled_(false), connect_timeout_ms_(0L), executor_(nullptr), callback_executor_(nullptr), error_handler_(nullptr) { string app_name = DetermineDefaultApplicationName(); user_agent_ = BuildStandardUserAgentString(app_name); // TODO(user): Resolve if we should do this or not. The application should // really decide where the certs are and do the call to // options.set_cacerts_path(DetermineDefaultCaCertsPath()). // But this is breaking, so we need to discuss the appropriate choice for // desktop clients like DriveFS with security. Do we ship a certs.pem from // drivefs or from boringssl? In any case, this is an application choice // not the SDK's choice. cacerts_path_ = client::DetermineDefaultCaCertsPath(); VLOG(1) << "Setting default cacerts_path=" << cacerts_path_; } HttpTransportOptions::~HttpTransportOptions() {} thread::Executor* HttpTransportOptions::executor() const { if (!executor_) { return thread::Executor::DefaultExecutor(); } return executor_; } thread::Executor* HttpTransportOptions::callback_executor() const { if (!callback_executor_) { return thread::SingletonInlineExecutor(); } return callback_executor_; } const char HttpTransportOptions::kGoogleApisUserAgent[] = "google-api-cpp-client"; const char HttpTransportOptions::kDisableSslVerification[] = "DisableSslVerification"; HttpTransport::HttpTransport(const HttpTransportOptions& options) : options_(options), scribe_(nullptr), in_shutdown_(false) { set_id("Unidentified"); } HttpTransport::~HttpTransport() { } void HttpTransport::Shutdown() { in_shutdown_ = true; } HttpTransport* HttpTransportLayerConfig::NewDefaultTransport( googleapis::util::Status* status) const { HttpTransportFactory* factory = default_transport_factory_.get(); if (!factory) { *status = StatusInternalError( "ResetDefaultTransportFactory has not been called."); return NULL; } return factory->NewWithOptions(default_options_); } /* static */ void HttpTransport::WriteRequestPreamble( const HttpRequest* request, DataWriter* writer) { // Write start-line if (!writer->Write(StrCat(request->http_method(), " ", request->url(), " HTTP/1.1", kCRLF)).ok()) { return; // error in status() } // Write headers const HttpHeaderMap& header_map = request->headers(); for (HttpHeaderMap::const_iterator it = header_map.begin(); it != header_map.end(); ++it) { // Dont bother checking for errors since we're probably good at this point. // They'll be in the status, which is sticky, so wont get lost anyway. writer->Write(StrCat(it->first, ": ", it->second, kCRLF)).IgnoreError(); } writer->Write(kCRLF).IgnoreError(); } /* static */ void HttpTransport::WriteRequest( const HttpRequest* request, DataWriter* writer) { WriteRequestPreamble(request, writer); DataReader* content = request->content_reader(); if (content) { // TODO(user): 20130820 // Check for chunked transfer encoding and, if so, write chunks // by iterating Write's using some chunk size. writer->Write(content).IgnoreError(); } } /* static */ void HttpTransport::ReadResponse(DataReader* reader, HttpResponse* response) { response->Clear(); const StringPiece kHttpIdentifier("HTTP/1.1 "); HttpRequestState* state = response->mutable_request_state(); string first_line; bool found = reader->ReadUntilPatternInclusive( kCRLF, &first_line); if (!found || !StringPiece(first_line).starts_with(kHttpIdentifier)) { state->set_transport_status(StatusUnknown("Expected leading 'HTTP/1.1'")); return; } int space = first_line.find(' '); int http_code = 0; if (space != StringPiece::npos) { safe_strto32(first_line.c_str() + space + 1, &http_code); } if (!http_code) { state->set_transport_status( StatusUnknown("Expected HTTP response code on first line")); return; } state->set_http_code(http_code); do { string header_line; if (!reader->ReadUntilPatternInclusive(kCRLF, &header_line)) { googleapis::util::Status error; if (reader->done()) { error = StatusUnknown("Expected headers to end with an empty CRLF"); } else { error = StatusUnknown("Expected header to end with CRLF"); } state->set_transport_status(error); return; } if (header_line == kCRLF) break; int colon = header_line.find(':'); if (colon == string::npos) { googleapis::util::Status error = StatusUnknown( StrCat("Expected ':' in header #", response->headers().size())); state->set_transport_status(error); return; } StringPiece line_piece(header_line); StringPiece name = line_piece.substr(0, colon); StringPiece value = line_piece.substr( colon + 1, header_line.size() - colon - 1 - kCRLF.size()); StripWhitespace(&name); StripWhitespace(&value); response->AddHeader(name.as_string(), value.as_string()); } while (true); // break above when header_line is empty // Remainder of reader is the response payload. response->body_writer()->Write(reader).IgnoreError(); } HttpTransport* HttpTransportLayerConfig::NewDefaultTransportOrDie() const { googleapis::util::Status status; HttpTransport* result = NewDefaultTransport(&status); if (!result) { LOG(FATAL) << "Could not create transport."; } return result; } HttpTransport* HttpTransportFactory::NewWithOptions( const HttpTransportOptions& options) { HttpTransport* transport = DoAlloc(options); if (scribe_.get()) { transport->set_scribe(scribe_.get()); } return transport; } void HttpTransportFactory::reset_scribe(HttpScribe* scribe) { scribe_.reset(scribe); } HttpTransportFactory::HttpTransportFactory() : config_(NULL), default_id_("UNKNOWN") { } HttpTransportFactory::HttpTransportFactory( const HttpTransportLayerConfig* config) : config_(config), default_id_("UNKNOWN") { } HttpTransportFactory::~HttpTransportFactory() { } } // namespace client } // namespace googleapis <file_sep>/service_apis/youtube/google/youtube_api/live_broadcast_content_details.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_LIVE_BROADCAST_CONTENT_DETAILS_H_ #define GOOGLE_YOUTUBE_API_LIVE_BROADCAST_CONTENT_DETAILS_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/monitor_stream_info.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Detailed settings of a broadcast. * * @ingroup DataObject */ class LiveBroadcastContentDetails : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static LiveBroadcastContentDetails* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveBroadcastContentDetails(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit LiveBroadcastContentDetails(Json::Value* storage); /** * Standard destructor. */ virtual ~LiveBroadcastContentDetails(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::LiveBroadcastContentDetails</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::LiveBroadcastContentDetails"); } /** * Determine if the '<code>boundStreamId</code>' attribute was set. * * @return true if the '<code>boundStreamId</code>' attribute was set. */ bool has_bound_stream_id() const { return Storage().isMember("boundStreamId"); } /** * Clears the '<code>boundStreamId</code>' attribute. */ void clear_bound_stream_id() { MutableStorage()->removeMember("boundStreamId"); } /** * Get the value of the '<code>boundStreamId</code>' attribute. */ const StringPiece get_bound_stream_id() const { const Json::Value& v = Storage("boundStreamId"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>boundStreamId</code>' attribute. * * This value uniquely identifies the live stream bound to the broadcast. * * @param[in] value The new value. */ void set_bound_stream_id(const StringPiece& value) { *MutableStorage("boundStreamId") = value.data(); } /** * Determine if the '<code>boundStreamLastUpdateTimeMs</code>' attribute was * set. * * @return true if the '<code>boundStreamLastUpdateTimeMs</code>' attribute * was set. */ bool has_bound_stream_last_update_time_ms() const { return Storage().isMember("boundStreamLastUpdateTimeMs"); } /** * Clears the '<code>boundStreamLastUpdateTimeMs</code>' attribute. */ void clear_bound_stream_last_update_time_ms() { MutableStorage()->removeMember("boundStreamLastUpdateTimeMs"); } /** * Get the value of the '<code>boundStreamLastUpdateTimeMs</code>' attribute. */ client::DateTime get_bound_stream_last_update_time_ms() const { const Json::Value& storage = Storage("boundStreamLastUpdateTimeMs"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>boundStreamLastUpdateTimeMs</code>' attribute. * * The date and time that the live stream referenced by boundStreamId was last * updated. * * @param[in] value The new value. */ void set_bound_stream_last_update_time_ms(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("boundStreamLastUpdateTimeMs")); } /** * Determine if the '<code>closedCaptionsType</code>' attribute was set. * * @return true if the '<code>closedCaptionsType</code>' attribute was set. */ bool has_closed_captions_type() const { return Storage().isMember("closedCaptionsType"); } /** * Clears the '<code>closedCaptionsType</code>' attribute. */ void clear_closed_captions_type() { MutableStorage()->removeMember("closedCaptionsType"); } /** * Get the value of the '<code>closedCaptionsType</code>' attribute. */ const StringPiece get_closed_captions_type() const { const Json::Value& v = Storage("closedCaptionsType"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>closedCaptionsType</code>' attribute. * @param[in] value The new value. */ void set_closed_captions_type(const StringPiece& value) { *MutableStorage("closedCaptionsType") = value.data(); } /** * Determine if the '<code>enableClosedCaptions</code>' attribute was set. * * @return true if the '<code>enableClosedCaptions</code>' attribute was set. */ bool has_enable_closed_captions() const { return Storage().isMember("enableClosedCaptions"); } /** * Clears the '<code>enableClosedCaptions</code>' attribute. */ void clear_enable_closed_captions() { MutableStorage()->removeMember("enableClosedCaptions"); } /** * Get the value of the '<code>enableClosedCaptions</code>' attribute. */ bool get_enable_closed_captions() const { const Json::Value& storage = Storage("enableClosedCaptions"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>enableClosedCaptions</code>' attribute. * * This setting indicates whether HTTP POST closed captioning is enabled for * this broadcast. The ingestion URL of the closed captions is returned * through the liveStreams API. This is mutually exclusive with using the * closed_captions_type property, and is equivalent to setting * closed_captions_type to CLOSED_CAPTIONS_HTTP_POST. * * @param[in] value The new value. */ void set_enable_closed_captions(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("enableClosedCaptions")); } /** * Determine if the '<code>enableContentEncryption</code>' attribute was set. * * @return true if the '<code>enableContentEncryption</code>' attribute was * set. */ bool has_enable_content_encryption() const { return Storage().isMember("enableContentEncryption"); } /** * Clears the '<code>enableContentEncryption</code>' attribute. */ void clear_enable_content_encryption() { MutableStorage()->removeMember("enableContentEncryption"); } /** * Get the value of the '<code>enableContentEncryption</code>' attribute. */ bool get_enable_content_encryption() const { const Json::Value& storage = Storage("enableContentEncryption"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>enableContentEncryption</code>' attribute. * * This setting indicates whether YouTube should enable content encryption for * the broadcast. * * @param[in] value The new value. */ void set_enable_content_encryption(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("enableContentEncryption")); } /** * Determine if the '<code>enableDvr</code>' attribute was set. * * @return true if the '<code>enableDvr</code>' attribute was set. */ bool has_enable_dvr() const { return Storage().isMember("enableDvr"); } /** * Clears the '<code>enableDvr</code>' attribute. */ void clear_enable_dvr() { MutableStorage()->removeMember("enableDvr"); } /** * Get the value of the '<code>enableDvr</code>' attribute. */ bool get_enable_dvr() const { const Json::Value& storage = Storage("enableDvr"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>enableDvr</code>' attribute. * * This setting determines whether viewers can access DVR controls while * watching the video. DVR controls enable the viewer to control the video * playback experience by pausing, rewinding, or fast forwarding content. The * default value for this property is true. * * * * Important: You must set the value to true and also set the enableArchive * property's value to true if you want to make playback available immediately * after the broadcast ends. * * @param[in] value The new value. */ void set_enable_dvr(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("enableDvr")); } /** * Determine if the '<code>enableEmbed</code>' attribute was set. * * @return true if the '<code>enableEmbed</code>' attribute was set. */ bool has_enable_embed() const { return Storage().isMember("enableEmbed"); } /** * Clears the '<code>enableEmbed</code>' attribute. */ void clear_enable_embed() { MutableStorage()->removeMember("enableEmbed"); } /** * Get the value of the '<code>enableEmbed</code>' attribute. */ bool get_enable_embed() const { const Json::Value& storage = Storage("enableEmbed"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>enableEmbed</code>' attribute. * * This setting indicates whether the broadcast video can be played in an * embedded player. If you choose to archive the video (using the * enableArchive property), this setting will also apply to the archived * video. * * @param[in] value The new value. */ void set_enable_embed(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("enableEmbed")); } /** * Determine if the '<code>enableLowLatency</code>' attribute was set. * * @return true if the '<code>enableLowLatency</code>' attribute was set. */ bool has_enable_low_latency() const { return Storage().isMember("enableLowLatency"); } /** * Clears the '<code>enableLowLatency</code>' attribute. */ void clear_enable_low_latency() { MutableStorage()->removeMember("enableLowLatency"); } /** * Get the value of the '<code>enableLowLatency</code>' attribute. */ bool get_enable_low_latency() const { const Json::Value& storage = Storage("enableLowLatency"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>enableLowLatency</code>' attribute. * * Indicates whether this broadcast has low latency enabled. * * @param[in] value The new value. */ void set_enable_low_latency(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("enableLowLatency")); } /** * Determine if the '<code>monitorStream</code>' attribute was set. * * @return true if the '<code>monitorStream</code>' attribute was set. */ bool has_monitor_stream() const { return Storage().isMember("monitorStream"); } /** * Clears the '<code>monitorStream</code>' attribute. */ void clear_monitor_stream() { MutableStorage()->removeMember("monitorStream"); } /** * Get a reference to the value of the '<code>monitorStream</code>' attribute. */ const MonitorStreamInfo get_monitor_stream() const; /** * Gets a reference to a mutable value of the '<code>monitorStream</code>' * property. * * The monitorStream object contains information about the monitor stream, * which the broadcaster can use to review the event content before the * broadcast stream is shown publicly. * * @return The result can be modified to change the attribute value. */ MonitorStreamInfo mutable_monitorStream(); /** * Determine if the '<code>projection</code>' attribute was set. * * @return true if the '<code>projection</code>' attribute was set. */ bool has_projection() const { return Storage().isMember("projection"); } /** * Clears the '<code>projection</code>' attribute. */ void clear_projection() { MutableStorage()->removeMember("projection"); } /** * Get the value of the '<code>projection</code>' attribute. */ const StringPiece get_projection() const { const Json::Value& v = Storage("projection"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>projection</code>' attribute. * * The projection format of this broadcast. This defaults to rectangular. * * @param[in] value The new value. */ void set_projection(const StringPiece& value) { *MutableStorage("projection") = value.data(); } /** * Determine if the '<code>recordFromStart</code>' attribute was set. * * @return true if the '<code>recordFromStart</code>' attribute was set. */ bool has_record_from_start() const { return Storage().isMember("recordFromStart"); } /** * Clears the '<code>recordFromStart</code>' attribute. */ void clear_record_from_start() { MutableStorage()->removeMember("recordFromStart"); } /** * Get the value of the '<code>recordFromStart</code>' attribute. */ bool get_record_from_start() const { const Json::Value& storage = Storage("recordFromStart"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>recordFromStart</code>' attribute. * * Automatically start recording after the event goes live. The default value * for this property is true. * * * * Important: You must also set the enableDvr property's value to true if you * want the playback to be available immediately after the broadcast ends. If * you set this property's value to true but do not also set the enableDvr * property to true, there may be a delay of around one day before the * archived video will be available for playback. * * @param[in] value The new value. */ void set_record_from_start(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("recordFromStart")); } /** * Determine if the '<code>startWithSlate</code>' attribute was set. * * @return true if the '<code>startWithSlate</code>' attribute was set. */ bool has_start_with_slate() const { return Storage().isMember("startWithSlate"); } /** * Clears the '<code>startWithSlate</code>' attribute. */ void clear_start_with_slate() { MutableStorage()->removeMember("startWithSlate"); } /** * Get the value of the '<code>startWithSlate</code>' attribute. */ bool get_start_with_slate() const { const Json::Value& storage = Storage("startWithSlate"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>startWithSlate</code>' attribute. * * This setting indicates whether the broadcast should automatically begin * with an in-stream slate when you update the broadcast's status to live. * After updating the status, you then need to send a liveCuepoints.insert * request that sets the cuepoint's eventState to end to remove the in-stream * slate and make your broadcast stream visible to viewers. * * @param[in] value The new value. */ void set_start_with_slate(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("startWithSlate")); } private: void operator=(const LiveBroadcastContentDetails&); }; // LiveBroadcastContentDetails } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_LIVE_BROADCAST_CONTENT_DETAILS_H_ <file_sep>/service_apis/youtube/google/youtube_api/video_recording_details.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_VIDEO_RECORDING_DETAILS_H_ #define GOOGLE_YOUTUBE_API_VIDEO_RECORDING_DETAILS_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/client/util/date_time.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/geo_point.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Recording information associated with the video. * * @ingroup DataObject */ class VideoRecordingDetails : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static VideoRecordingDetails* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoRecordingDetails(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoRecordingDetails(Json::Value* storage); /** * Standard destructor. */ virtual ~VideoRecordingDetails(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::VideoRecordingDetails</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::VideoRecordingDetails"); } /** * Determine if the '<code>location</code>' attribute was set. * * @return true if the '<code>location</code>' attribute was set. */ bool has_location() const { return Storage().isMember("location"); } /** * Clears the '<code>location</code>' attribute. */ void clear_location() { MutableStorage()->removeMember("location"); } /** * Get a reference to the value of the '<code>location</code>' attribute. */ const GeoPoint get_location() const; /** * Gets a reference to a mutable value of the '<code>location</code>' * property. * * The geolocation information associated with the video. * * @return The result can be modified to change the attribute value. */ GeoPoint mutable_location(); /** * Determine if the '<code>locationDescription</code>' attribute was set. * * @return true if the '<code>locationDescription</code>' attribute was set. */ bool has_location_description() const { return Storage().isMember("locationDescription"); } /** * Clears the '<code>locationDescription</code>' attribute. */ void clear_location_description() { MutableStorage()->removeMember("locationDescription"); } /** * Get the value of the '<code>locationDescription</code>' attribute. */ const StringPiece get_location_description() const { const Json::Value& v = Storage("locationDescription"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>locationDescription</code>' attribute. * * The text description of the location where the video was recorded. * * @param[in] value The new value. */ void set_location_description(const StringPiece& value) { *MutableStorage("locationDescription") = value.data(); } /** * Determine if the '<code>recordingDate</code>' attribute was set. * * @return true if the '<code>recordingDate</code>' attribute was set. */ bool has_recording_date() const { return Storage().isMember("recordingDate"); } /** * Clears the '<code>recordingDate</code>' attribute. */ void clear_recording_date() { MutableStorage()->removeMember("recordingDate"); } /** * Get the value of the '<code>recordingDate</code>' attribute. */ client::DateTime get_recording_date() const { const Json::Value& storage = Storage("recordingDate"); return client::JsonValueToCppValueHelper<client::DateTime >(storage); } /** * Change the '<code>recordingDate</code>' attribute. * * The date and time when the video was recorded. The value is specified in * ISO 8601 (YYYY-MM-DDThh:mm:ss.sssZ) format. * * @param[in] value The new value. */ void set_recording_date(client::DateTime value) { client::SetJsonValueFromCppValueHelper<client::DateTime >( value, MutableStorage("recordingDate")); } private: void operator=(const VideoRecordingDetails&); }; // VideoRecordingDetails } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_VIDEO_RECORDING_DETAILS_H_ <file_sep>/src/samples/calendar_sample_main.cc /* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ // // This is a sample application illustrating the use of the GoogleApis C++ // Client. The application makes calls into the Google Calendar service. // The application itself is not particularly useful, rather it just // illustrates how to interact with a live service. // // Usage: // // Calendar requires OAuth2 authorization, which in turn requires that the // application be authorized using the https://code.google.com/apis/console. // You will need to do this yourself -- creating your own client ID and // secret in order to run it. // // For this example, you want to create an Installed Application // From the "API Access" tab, create an "Installed Application" client ID // Download the client secrets JSON file. // From the "Services" tab, give access to the Calendar API. // // If you already know the ID and secret, you can create the json file yourself // from teh following example (including outer {}). Replace the "..." with // your values, but be sure to quote them (i.e. "mysecret" } // { // "installed": { // "client_id": "...", // "client_secret": "..." // } // } // // // When the program starts up you will be asked to authorize by copying // a URL into a browser and copying the response back. From there the // program executes a shell that takes commands. Type 'help' for a list // of current commands and 'quit' to exit. #include <iostream> using std::cout; using std::endl; using std::ostream; // NOLINT #include <memory> #include "googleapis/client/auth/file_credential_store.h" #include "googleapis/client/auth/oauth2_authorization.h" #include "googleapis/client/data/data_reader.h" #if HAVE_OPENSSL #include "googleapis/client/data/openssl_codec.h" #endif #include "googleapis/client/transport/curl_http_transport.h" #include "googleapis/client/transport/http_authorization.h" #include "googleapis/client/transport/http_transport.h" #include "googleapis/client/transport/http_request_batch.h" #include "googleapis/client/util/status.h" #include "googleapis/strings/strcat.h" #include "google/calendar_api/calendar_api.h" // NOLINT namespace googleapis { using std::cin; using std::cout; using std::cerr; using std::endl; using google_calendar_api::Calendar; using google_calendar_api::CalendarList; using google_calendar_api::CalendarListEntry; using google_calendar_api::CalendarsResource_DeleteMethod; using google_calendar_api::CalendarsResource_InsertMethod; using google_calendar_api::CalendarListResource_ListMethod; using google_calendar_api::CalendarService; using google_calendar_api::Event; using google_calendar_api::Events; using google_calendar_api::EventsResource_GetMethod; using google_calendar_api::EventsResource_InsertMethod; using google_calendar_api::EventsResource_ListMethod; using google_calendar_api::EventsResource_ListMethodPager; using google_calendar_api::EventsResource_PatchMethod; using google_calendar_api::EventsResource_UpdateMethod; using client::ClientServiceRequest; using client::DateTime; using client::FileCredentialStoreFactory; using client::HttpRequestBatch; using client::HttpResponse; using client::HttpTransport; using client::HttpTransportLayerConfig; using client::JsonCppArray; using client::OAuth2Credential; using client::OAuth2AuthorizationFlow; using client::OAuth2RequestOptions; #if HAVE_OPENSSL using client::OpenSslCodecFactory; #endif using client::StatusCanceled; using client::StatusInvalidArgument; using client::StatusOk; const char kSampleStepPrefix[] = "SAMPLE: "; static googleapis::util::Status PromptShellForAuthorizationCode( OAuth2AuthorizationFlow* flow, const OAuth2RequestOptions& options, string* authorization_code) { string url = flow->GenerateAuthorizationCodeRequestUrlWithOptions(options); std::cout << "Enter the following URL into a browser:\n" << url << std::endl; std::cout << std::endl; std::cout << "Enter the browser's response to confirm authorization: "; authorization_code->clear(); std::cin >> *authorization_code; if (authorization_code->empty()) { return StatusCanceled("Canceled"); } else { return StatusOk(); } } static googleapis::util::Status ValidateUserName(const string& name) { if (name.find("/") != string::npos) { return StatusInvalidArgument("UserNames cannot contain '/'"); } else if (name == "." || name == "..") { return StatusInvalidArgument( StrCat("'", name, "' is not a valid UserName")); } return StatusOk(); } void DisplayError(ClientServiceRequest* request) { const HttpResponse& response = *request->http_response(); std::cout << "==== ERROR ====" << std::endl; std::cout << "Status: " << response.status().error_message() << std::endl; if (response.transport_status().ok()) { std::cout << "HTTP Status Code = " << response.http_code() << std::endl; std::cout << std::endl << response.body_reader()->RemainderToString() << std::endl; } std::cout << std::endl; } void Display(const string& prefix, const CalendarListEntry& entry) { std::cout << prefix << "CalendarListEntry" << std::endl; std::cout << prefix << " ID: " << entry.get_id() << std::endl; std::cout << prefix << " Summary: " << entry.get_summary() << std::endl; if (entry.has_description()) { std::cout << prefix << " Description: " << entry.get_description() << std::endl; } } void Display(const string& prefix, const Calendar& entry) { std::cout << prefix << "Calendar" << std::endl; std::cout << prefix << " ID: " << entry.get_id() << std::endl; std::cout << prefix << " Summary: " << entry.get_summary() << std::endl; if (!entry.get_description().empty()) { std::cout << prefix << " Description: " << entry.get_description() << std::endl; } } void Display(const string& prefix, const Event& event) { std::cout << prefix << "Event" << std::endl; std::cout << prefix << " ID: " << event.get_id() << std::endl; if (event.has_summary()) { std::cout << prefix << " Summary: " << event.get_summary() << std::endl; } if (event.get_start().has_date_time()) { std::cout << prefix << " Start Time: " << event.get_start().get_date_time().ToString() << std::endl; } if (event.get_end().has_date_time()) { std::cout << prefix << " End Time: " << event.get_end().get_date_time().ToString() << std::endl; } } template <class LIST, typename ELEM> void DisplayList( const string& prefix, const string& title, const LIST& list) { std::cout << prefix << "==== " << title << " ====" << std::endl; string sub_prefix = StrCat(prefix, " "); bool first = true; const JsonCppArray<ELEM>& items = list.get_items(); for (typename JsonCppArray<ELEM>::const_iterator it = items.begin(); it != items.end(); ++it) { if (first) { first = false; } else { std::cout << std::endl; } Display(sub_prefix, *it); } if (first) { std::cout << sub_prefix << "<no items>" << std::endl; } } class CalendarSample { public: static googleapis::util::Status Startup(int argc, char* argv[]); void Run(); private: // Gets authorization to access the user's personal calendar data. googleapis::util::Status Authorize(); // Prints some current calendar data to the console to show the effects // from the calls that the sample has made. void ShowCalendars(); // Demonstrates adding a new resource. For this example, it is a calendar. // Returns a proxy to the calendar added in the Calendar Service (cloud). // We only really need the ID so that's all we return. string AddCalendar(); // Demonstrates adding an embedded resource. // For this example it is a calendar event. // // This takes a calendar ID such as that returned by AddCalendar(). // We'll take a configured event as input and modify its ID with the // ID assigned by the Calendar Service (cloud). We could have just returned // the ID as in the case of Calendar but we are doing it differently for // demonstration purposes. void AddEvent(const string& calendar_id, Event* event); // Demonstrates using a ServiceRequestPager to list all the events on the // given calendar. void PageThroughAllEvents(const string& calendar_id, int events_per_page); // Demonstrates deleting a resource. For this example, it is a calendar. // We are deleting the calendar in the Calendar Service (cloud) that // has the given calendar_id. void DeleteCalendar(const string& calendar_id); // Demonstrates getting a resource. // For this example, it is a calendar event. // Returns the final status for the request. If not ok() then event wasn't // populated. googleapis::util::Status GetEvent( const string& calendar_id, const string& event_id, Event* event); // Demonstrates patching a resource. // For this example, it is a calendar event. void PatchEvent(const string& calendar_id, const Event& event); // Demonstrates updating a resource. // For this example, it is a calendar event. void UpdateEvent(const string& calendar_id, const Event& event); OAuth2Credential credential_; static std::unique_ptr<CalendarService> service_; static std::unique_ptr<OAuth2AuthorizationFlow> flow_; static std::unique_ptr<HttpTransportLayerConfig> config_; }; // static std::unique_ptr<CalendarService> CalendarSample::service_; std::unique_ptr<OAuth2AuthorizationFlow> CalendarSample::flow_; std::unique_ptr<HttpTransportLayerConfig> CalendarSample::config_; /* static */ util::Status CalendarSample::Startup(int argc, char* argv[]) { if ((argc < 2) || (argc > 3)) { string error = StrCat("Invalid Usage:\n", argv[0], " <client_secrets_file> [<cacerts_path>]\n"); return StatusInvalidArgument(error); } // Set up HttpTransportLayer. googleapis::util::Status status; config_.reset(new HttpTransportLayerConfig); client::HttpTransportFactory* factory = new client::CurlHttpTransportFactory(config_.get()); config_->ResetDefaultTransportFactory(factory); if (argc > 2) { config_->mutable_default_transport_options()->set_cacerts_path(argv[2]); } // Set up OAuth 2.0 flow for getting credentials to access personal data. const string client_secrets_file = argv[1]; flow_.reset(OAuth2AuthorizationFlow::MakeFlowFromClientSecretsPath( client_secrets_file, config_->NewDefaultTransportOrDie(), &status)); if (!status.ok()) return status; flow_->set_default_scopes(CalendarService::SCOPES::CALENDAR); flow_->mutable_client_spec()->set_redirect_uri( OAuth2AuthorizationFlow::kOutOfBandUrl); flow_->set_authorization_code_callback( NewPermanentCallback(&PromptShellForAuthorizationCode, flow_.get())); string home_path; status = FileCredentialStoreFactory::GetSystemHomeDirectoryStorePath( &home_path); if (status.ok()) { FileCredentialStoreFactory store_factory(home_path); // Use a credential store to save the credentials between runs so that // we dont need to get permission again the next time we run. We are // going to encrypt the data in the store, but leave it to the OS to // protect access since we do not authenticate users in this sample. #if HAVE_OPENSSL OpenSslCodecFactory* openssl_factory = new OpenSslCodecFactory; status = openssl_factory->SetPassphrase( flow_->client_spec().client_secret()); if (!status.ok()) return status; store_factory.set_codec_factory(openssl_factory); #endif flow_->ResetCredentialStore( store_factory.NewCredentialStore("CalendarSample", &status)); } if (!status.ok()) return status; // Now we'll initialize the calendar service proxy that we'll use // to interact with the calendar from this sample program. HttpTransport* transport = config_->NewDefaultTransport(&status); if (!status.ok()) return status; service_.reset(new CalendarService(transport)); return status; } util::Status CalendarSample::Authorize() { std::cout << std::endl << "Welcome to the Google APIs for C++ CalendarSample.\n" << " You will need to authorize this program to look at your calendar.\n" << " If you would like to save these credentials between runs\n" << " (or restore from an earlier run) then enter a Google Email " "Address.\n" << " Otherwise just press return.\n" << std::endl << " Address: "; string email; std::getline(std::cin, email); if (!email.empty()) { googleapis::util::Status status = ValidateUserName(email); if (!status.ok()) { return status; } } OAuth2RequestOptions options; options.email = email; googleapis::util::Status status = flow_->RefreshCredentialWithOptions(options, &credential_); if (!status.ok()) { return status; } credential_.set_flow(flow_.get()); std::cout << "Authorized " << email << std::endl; return StatusOk(); } void CalendarSample::ShowCalendars() { std::unique_ptr<CalendarListResource_ListMethod> method( service_->get_calendar_list().NewListMethod(&credential_)); std::unique_ptr<CalendarList> calendar_list(CalendarList::New()); if (!method->ExecuteAndParseResponse(calendar_list.get()).ok()) { DisplayError(method.get()); return; } DisplayList<CalendarList, CalendarListEntry>( "", "CalendarList", *calendar_list); std::cout << std::endl; } string CalendarSample::AddCalendar() { std::unique_ptr<Calendar> calendar(Calendar::New()); calendar->set_summary("Calendar added by CalendarSample"); std::unique_ptr<CalendarsResource_InsertMethod> method( service_->get_calendars().NewInsertMethod(&credential_, *calendar)); if (!method->ExecuteAndParseResponse(calendar.get()).ok()) { DisplayError(method.get()); return ""; } string result = calendar->get_id().as_string(); std::cout << "Added new calendar ID=" << result << ":" << std::endl; Display(" ", *calendar); std::cout << std::endl; return result; } void CalendarSample::AddEvent(const string& calendar_id, Event* event) { std::unique_ptr<EventsResource_InsertMethod> method( service_->get_events().NewInsertMethod( &credential_, calendar_id, *event)); if (!method->ExecuteAndParseResponse(event).ok()) { DisplayError(method.get()); return; } std::cout << "Added new event ID=" << event->get_id() << ":" << std::endl; Display(" ", *event); std::cout << std::endl; } void CalendarSample::PageThroughAllEvents( const string& calendar_id, int num_per_page) { std::cout << "All Events" << std::endl; std::unique_ptr<EventsResource_ListMethodPager> pager( service_->get_events().NewListMethodPager(&credential_, calendar_id)); pager->request()->set_max_results(num_per_page); while (pager->NextPage()) { DisplayList<Events, Event>(" ", "EventList", *pager->data()); } } util::Status CalendarSample::GetEvent( const string& calendar_id, const string& event_id, Event* event) { std::unique_ptr<EventsResource_GetMethod> method( service_->get_events().NewGetMethod( &credential_, calendar_id, event_id)); return method->ExecuteAndParseResponse(event); } void CalendarSample::PatchEvent( const string& calendar_id, const Event& event) { std::unique_ptr<EventsResource_PatchMethod> method( service_->get_events().NewPatchMethod( &credential_, calendar_id, event.get_id(), event)); if (!method->Execute().ok()) { DisplayError(method.get()); return; } std::unique_ptr<Event> cloud_event(Event::New()); googleapis::util::Status status = GetEvent(calendar_id, event.get_id().as_string(), cloud_event.get()); if (status.ok()) { std::cout << "Patched event:" << std::endl; Display(" ", *cloud_event); } else { std::cout << "** Could not get patched event: " << status.error_message() << std::endl; } std::cout << std::endl; } void CalendarSample::UpdateEvent( const string& calendar_id, const Event& event) { std::unique_ptr<EventsResource_UpdateMethod> method( service_->get_events().NewUpdateMethod( &credential_, calendar_id, event.get_id(), event)); if (!method->Execute().ok()) { DisplayError(method.get()); return; } std::unique_ptr<Event> cloud_event(Event::New()); googleapis::util::Status status = GetEvent(calendar_id, event.get_id().as_string(), cloud_event.get()); if (status.ok()) { std::cout << "Updated event:" << std::endl; Display(" ", *cloud_event); } else { std::cout << "** Could not get updated event: " << status.error_message() << std::endl; } std::cout << std::endl; } void CalendarSample::DeleteCalendar(const string& id) { std::unique_ptr<CalendarsResource_DeleteMethod> method( service_->get_calendars().NewDeleteMethod(&credential_, id)); if (!method->Execute().ok()) { DisplayError(method.get()); return; } std::cout << "Deleted ID=" << id << std::endl; std::cout << std::endl; } void CalendarSample::Run() { std::cout << kSampleStepPrefix << "Getting User Authorization" << std::endl; googleapis::util::Status status = Authorize(); if (!status.ok()) { std::cout << "Could not authorize: " << status.error_message() << std::endl; return; } std::cout << std::endl << kSampleStepPrefix << "Showing Initial Calendars" << std::endl; ShowCalendars(); std::cout << std::endl << kSampleStepPrefix << "Adding Calendar" << std::endl; string calendar_id = AddCalendar(); std::cout << std::endl << kSampleStepPrefix << "Showing Updated Calendars" << std::endl; ShowCalendars(); DateTime now; std::unique_ptr<Event> event(Event::New()); event->set_summary("Calendar event added by CalendarSample"); event->mutable_start().set_date_time(now); event->mutable_end().set_date_time(DateTime(now.ToEpochTime() + 60 * 60)); std::cout << std::endl << kSampleStepPrefix << "Add Calendar Event" << std::endl; AddEvent(calendar_id, event.get()); std::cout << std::endl << kSampleStepPrefix << "Patch Calendar Event" << std::endl; event->clear_start(); event->clear_end(); event->set_summary("Event patched by CalendarSample"); PatchEvent(calendar_id, *event); std::cout << std::endl << kSampleStepPrefix << "Update Calendar Event" << std::endl; // An update requires a time. // Go back a year and one day to distinguish it from the old value. event->mutable_start().set_date_time( DateTime(now.ToEpochTime() - 60 * 60 * 24 * 367)); event->mutable_end().set_date_time( DateTime(now.ToEpochTime() - 60 * 60 * 24 * 366)); event->clear_summary(); UpdateEvent(calendar_id, *event); std::cout << std::endl << "Adding bulk events using a batch request" << std::endl; HttpRequestBatch batch(service_->transport()); batch.mutable_http_request()->set_credential(&credential_); for (int i = 0; i < 10; ++i) { std::unique_ptr<Event> the_event(Event::New()); // Space the events at hour intervals with 15 minute durations. the_event->set_summary(StrCat("Extra event ", i)); the_event->mutable_start().set_date_time( DateTime(now.ToEpochTime() + i * 60 * 60)); the_event->mutable_end().set_date_time( DateTime(now.ToEpochTime() + i * 60 * 60 + 15 * 60)); EventsResource_InsertMethod* method( service_->get_events().NewInsertMethod( &credential_, calendar_id, *the_event)); method->ConvertIntoHttpRequestBatchAndDestroy(&batch); } status = batch.Execute(); if (!status.ok()) { std::cout << "Entire batch execution failed: " << status.error_message() << std::endl; } for (int i = 0; i < 10; ++i) { HttpResponse* response = batch.requests()[i]->response(); if (!response->ok()) { string detail; if (response->body_reader()) { detail = response->body_reader()->RemainderToString(); } else { detail = "No response data available."; } std::cout << "Error adding batched event " << i << std::endl << response->status().ToString() << std::endl << detail << std::endl; } } PageThroughAllEvents(calendar_id, 7); std::cout << std::endl << kSampleStepPrefix << "Deleting Calendar" << std::endl; DeleteCalendar(calendar_id); std::cout << std::endl << kSampleStepPrefix << "Showing Final Calendars" << std::endl; ShowCalendars(); } } // namespace googleapis using namespace googleapis; int main(int argc, char* argv[]) { googleapis::util::Status status = CalendarSample::Startup(argc, argv); if (!status.ok()) { std::cerr << "Could not initialize application." << std::endl; std::cerr << status.error_message() << std::endl; return -1; } CalendarSample sample; sample.Run(); std::cout << "Done!" << std::endl; return 0; } <file_sep>/service_apis/youtube/google/youtube_api/video_content_details.h // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. // This code was generated by google-apis-code-generator 1.5.1 // ---------------------------------------------------------------------------- // NOTE: This file is generated from Google APIs Discovery Service. // Service: // YouTube Data API (youtube/v3) // Generated from: // Version: v3 // Revision: 20170130 // Generated by: // Tool: google-apis-code-generator 1.5.1 // C++: 0.1.4 #ifndef GOOGLE_YOUTUBE_API_VIDEO_CONTENT_DETAILS_H_ #define GOOGLE_YOUTUBE_API_VIDEO_CONTENT_DETAILS_H_ #include <string> #include "googleapis/base/macros.h" #include "googleapis/client/data/jsoncpp_data.h" #include "googleapis/strings/stringpiece.h" #include "google/youtube_api/access_policy.h" #include "google/youtube_api/content_rating.h" #include "google/youtube_api/video_content_details_region_restriction.h" namespace Json { class Value; } // namespace Json namespace google_youtube_api { using namespace googleapis; /** * Details about the content of a YouTube Video. * * @ingroup DataObject */ class VideoContentDetails : public client::JsonCppData { public: /** * Creates a new default instance. * * @return Ownership is passed back to the caller. */ static VideoContentDetails* New(); /** * Standard constructor for an immutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoContentDetails(const Json::Value& storage); /** * Standard constructor for a mutable data object instance. * * @param[in] storage The underlying data storage for this instance. */ explicit VideoContentDetails(Json::Value* storage); /** * Standard destructor. */ virtual ~VideoContentDetails(); /** * Returns a string denoting the type of this data object. * * @return <code>google_youtube_api::VideoContentDetails</code> */ const StringPiece GetTypeName() const { return StringPiece("google_youtube_api::VideoContentDetails"); } /** * Determine if the '<code>caption</code>' attribute was set. * * @return true if the '<code>caption</code>' attribute was set. */ bool has_caption() const { return Storage().isMember("caption"); } /** * Clears the '<code>caption</code>' attribute. */ void clear_caption() { MutableStorage()->removeMember("caption"); } /** * Get the value of the '<code>caption</code>' attribute. */ const StringPiece get_caption() const { const Json::Value& v = Storage("caption"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>caption</code>' attribute. * * The value of captions indicates whether the video has captions or not. * * @param[in] value The new value. */ void set_caption(const StringPiece& value) { *MutableStorage("caption") = value.data(); } /** * Determine if the '<code>contentRating</code>' attribute was set. * * @return true if the '<code>contentRating</code>' attribute was set. */ bool has_content_rating() const { return Storage().isMember("contentRating"); } /** * Clears the '<code>contentRating</code>' attribute. */ void clear_content_rating() { MutableStorage()->removeMember("contentRating"); } /** * Get a reference to the value of the '<code>contentRating</code>' attribute. */ const ContentRating get_content_rating() const; /** * Gets a reference to a mutable value of the '<code>contentRating</code>' * property. * * Specifies the ratings that the video received under various rating schemes. * * @return The result can be modified to change the attribute value. */ ContentRating mutable_contentRating(); /** * Determine if the '<code>countryRestriction</code>' attribute was set. * * @return true if the '<code>countryRestriction</code>' attribute was set. */ bool has_country_restriction() const { return Storage().isMember("countryRestriction"); } /** * Clears the '<code>countryRestriction</code>' attribute. */ void clear_country_restriction() { MutableStorage()->removeMember("countryRestriction"); } /** * Get a reference to the value of the '<code>countryRestriction</code>' * attribute. */ const AccessPolicy get_country_restriction() const; /** * Gets a reference to a mutable value of the * '<code>countryRestriction</code>' property. * * The countryRestriction object contains information about the countries * where a video is (or is not) viewable. * * @return The result can be modified to change the attribute value. */ AccessPolicy mutable_countryRestriction(); /** * Determine if the '<code>definition</code>' attribute was set. * * @return true if the '<code>definition</code>' attribute was set. */ bool has_definition() const { return Storage().isMember("definition"); } /** * Clears the '<code>definition</code>' attribute. */ void clear_definition() { MutableStorage()->removeMember("definition"); } /** * Get the value of the '<code>definition</code>' attribute. */ const StringPiece get_definition() const { const Json::Value& v = Storage("definition"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>definition</code>' attribute. * * The value of definition indicates whether the video is available in high * definition or only in standard definition. * * @param[in] value The new value. */ void set_definition(const StringPiece& value) { *MutableStorage("definition") = value.data(); } /** * Determine if the '<code>dimension</code>' attribute was set. * * @return true if the '<code>dimension</code>' attribute was set. */ bool has_dimension() const { return Storage().isMember("dimension"); } /** * Clears the '<code>dimension</code>' attribute. */ void clear_dimension() { MutableStorage()->removeMember("dimension"); } /** * Get the value of the '<code>dimension</code>' attribute. */ const StringPiece get_dimension() const { const Json::Value& v = Storage("dimension"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>dimension</code>' attribute. * * The value of dimension indicates whether the video is available in 3D or in * 2D. * * @param[in] value The new value. */ void set_dimension(const StringPiece& value) { *MutableStorage("dimension") = value.data(); } /** * Determine if the '<code>duration</code>' attribute was set. * * @return true if the '<code>duration</code>' attribute was set. */ bool has_duration() const { return Storage().isMember("duration"); } /** * Clears the '<code>duration</code>' attribute. */ void clear_duration() { MutableStorage()->removeMember("duration"); } /** * Get the value of the '<code>duration</code>' attribute. */ const StringPiece get_duration() const { const Json::Value& v = Storage("duration"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>duration</code>' attribute. * * The length of the video. The tag value is an ISO 8601 duration in the * format PT#M#S, in which the letters PT indicate that the value specifies a * period of time, and the letters M and S refer to length in minutes and * seconds, respectively. The # characters preceding the M and S letters are * both integers that specify the number of minutes (or seconds) of the video. * For example, a value of PT15M51S indicates that the video is 15 minutes and * 51 seconds long. * * @param[in] value The new value. */ void set_duration(const StringPiece& value) { *MutableStorage("duration") = value.data(); } /** * Determine if the '<code>hasCustomThumbnail</code>' attribute was set. * * @return true if the '<code>hasCustomThumbnail</code>' attribute was set. */ bool has_has_custom_thumbnail() const { return Storage().isMember("hasCustomThumbnail"); } /** * Clears the '<code>hasCustomThumbnail</code>' attribute. */ void clear_has_custom_thumbnail() { MutableStorage()->removeMember("hasCustomThumbnail"); } /** * Get the value of the '<code>hasCustomThumbnail</code>' attribute. */ bool get_has_custom_thumbnail() const { const Json::Value& storage = Storage("hasCustomThumbnail"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>hasCustomThumbnail</code>' attribute. * * Indicates whether the video uploader has provided a custom thumbnail image * for the video. This property is only visible to the video uploader. * * @param[in] value The new value. */ void set_has_custom_thumbnail(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("hasCustomThumbnail")); } /** * Determine if the '<code>licensedContent</code>' attribute was set. * * @return true if the '<code>licensedContent</code>' attribute was set. */ bool has_licensed_content() const { return Storage().isMember("licensedContent"); } /** * Clears the '<code>licensedContent</code>' attribute. */ void clear_licensed_content() { MutableStorage()->removeMember("licensedContent"); } /** * Get the value of the '<code>licensedContent</code>' attribute. */ bool get_licensed_content() const { const Json::Value& storage = Storage("licensedContent"); return client::JsonValueToCppValueHelper<bool >(storage); } /** * Change the '<code>licensedContent</code>' attribute. * * The value of is_license_content indicates whether the video is licensed * content. * * @param[in] value The new value. */ void set_licensed_content(bool value) { client::SetJsonValueFromCppValueHelper<bool >( value, MutableStorage("licensedContent")); } /** * Determine if the '<code>projection</code>' attribute was set. * * @return true if the '<code>projection</code>' attribute was set. */ bool has_projection() const { return Storage().isMember("projection"); } /** * Clears the '<code>projection</code>' attribute. */ void clear_projection() { MutableStorage()->removeMember("projection"); } /** * Get the value of the '<code>projection</code>' attribute. */ const StringPiece get_projection() const { const Json::Value& v = Storage("projection"); if (v == Json::Value::null) return StringPiece(""); return StringPiece(v.asCString()); } /** * Change the '<code>projection</code>' attribute. * * Specifies the projection format of the video. * * @param[in] value The new value. */ void set_projection(const StringPiece& value) { *MutableStorage("projection") = value.data(); } /** * Determine if the '<code>regionRestriction</code>' attribute was set. * * @return true if the '<code>regionRestriction</code>' attribute was set. */ bool has_region_restriction() const { return Storage().isMember("regionRestriction"); } /** * Clears the '<code>regionRestriction</code>' attribute. */ void clear_region_restriction() { MutableStorage()->removeMember("regionRestriction"); } /** * Get a reference to the value of the '<code>regionRestriction</code>' * attribute. */ const VideoContentDetailsRegionRestriction get_region_restriction() const; /** * Gets a reference to a mutable value of the '<code>regionRestriction</code>' * property. * * The regionRestriction object contains information about the countries where * a video is (or is not) viewable. The object will contain either the * contentDetails.regionRestriction.allowed property or the * contentDetails.regionRestriction.blocked property. * * @return The result can be modified to change the attribute value. */ VideoContentDetailsRegionRestriction mutable_regionRestriction(); private: void operator=(const VideoContentDetails&); }; // VideoContentDetails } // namespace google_youtube_api #endif // GOOGLE_YOUTUBE_API_VIDEO_CONTENT_DETAILS_H_
acfb7652e5ead93450ec6a1259404a90e1a71a90
[ "CMake", "Markdown", "Python", "C", "C++" ]
117
C++
yoshipaulbrophy/google-api-cpp-client
6a5dba71ffc17f0597ae5782584a95caf14070aa
72861005d3e4f471aa36e3ebb00bf9c87dabf81b
refs/heads/master
<file_sep>const express = require('express') const routes = require('./routes') const app = express() require("dotenv").config(); const port = process.env.PORT const mongoose = require('mongoose') const db_login = process.env.DB_LOGIN const db_password = process.env.DB_PASSWORD const url = `mongodb+srv://${db_login}:${db_password}@authproject.fmgfb.gcp.mongodb.net/authproject?retryWrites=true&w=majority`; mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true, }); const db = mongoose.connection db.once('open', _ => { console.log('Database connected:', url) }) db.on('error', err => { console.error('connection error:', err) }) app.use(express.json()); // ensinando ao express para utilizar formato json app.use(routes); app.use((error, req, res, next) => { res.status(error.httpStatusCode).json(error.message); }); app.listen(port, () => { console.log (`Rodando o aplicativo em localhost:${port}`) })
288319419878ba9893a188f9b43009631087deff
[ "JavaScript" ]
1
JavaScript
theusmoraes/Authenticator_Node_Backend
e0bad03b96c5e96cd88955c5403b643d79a0b6bd
075f3e55ffaca1eff9512b06efde9c25ac6e041b
refs/heads/master
<file_sep># setup-Hub # Usage See [action.yml](action.yml) Basic: ```yaml steps: - uses: actions/checkout@latest - uses: geertvdc/setup-hub@master - run: hub --version ``` # License The scripts and documentation in this project are released under the [MIT License](LICENSE) # Contributions Contributions are welcome! See [Contributor's Guide](docs/contributors.md) <file_sep>let tempDirectory = process.env['RUNNER_TEMP'] || ''; import * as core from '@actions/core'; import * as io from '@actions/io'; import * as exec from '@actions/exec'; import * as tc from '@actions/tool-cache'; import * as fs from 'fs'; import * as path from 'path'; import * as semver from 'semver'; import * as httpm from 'typed-rest-client/HttpClient'; const IS_WINDOWS = process.platform === 'win32'; if (!tempDirectory) { let baseLocation; if (IS_WINDOWS) { // On windows use the USERPROFILE env variable baseLocation = process.env['USERPROFILE'] || 'C:\\'; } else { if (process.platform === 'darwin') { baseLocation = '/Users'; } else { baseLocation = '/home'; } } tempDirectory = path.join(baseLocation, 'actions', 'temp'); } export async function getHub( version: string, ): Promise<void> { let toolPath = tc.find('hub', version); if (toolPath) { core.debug(`Tool found in cache ${toolPath}`); } else { let compressedFileExtension = ''; core.debug('Downloading hub from Github releases'); const downloadInfo = await getDownloadInfo(version); let hubBin = await tc.downloadTool(downloadInfo.url); compressedFileExtension = IS_WINDOWS ? '.zip' : '.tar.gz'; let hubFile = downloadInfo.url.substring(downloadInfo.url.lastIndexOf('/')); let tempDir: string = path.join( tempDirectory, 'temp_' + Math.floor(Math.random() * 2000000000) ); const hubDir = await unzipHubDownload( hubFile, compressedFileExtension, tempDir ); core.debug(`hub extracted to ${hubDir}`); toolPath = await tc.cacheDir( hubDir, 'hub', getCacheVersionString(version) ); } core.addPath(path.join(toolPath, 'bin')); } function getCacheVersionString(version: string) { const versionArray = version.split('.'); const major = versionArray[0]; const minor = versionArray.length > 1 ? versionArray[1] : '0'; const patch = versionArray.length > 2 ? versionArray[2] : '0'; return `${major}.${minor}.${patch}`; } function getFileEnding(file: string): string { let fileEnding = ''; if (file.endsWith('.tar')) { fileEnding = '.tar'; } else if (file.endsWith('.tar.gz')) { fileEnding = '.tar.gz'; } else if (file.endsWith('.zip')) { fileEnding = '.zip'; } else if (file.endsWith('.7z')) { fileEnding = '.7z'; } else { throw new Error(`${file} has an unsupported file extension`); } return fileEnding; } async function extractFiles( file: string, fileEnding: string, destinationFolder: string ): Promise<void> { const stats = fs.statSync(file); if (!stats) { throw new Error(`Failed to extract ${file} - it doesn't exist`); } else if (stats.isDirectory()) { throw new Error(`Failed to extract ${file} - it is a directory`); } if ('.tar' === fileEnding || '.tar.gz' === fileEnding) { await tc.extractTar(file, destinationFolder); } else if ('.zip' === fileEnding) { await tc.extractZip(file, destinationFolder); } else { // fall through and use sevenZip await tc.extract7z(file, destinationFolder); } } async function unzipHubDownload( repoRoot: string, fileEnding: string, destinationFolder: string, extension?: string ): Promise<string> { // Create the destination folder if it doesn't exist await io.mkdirP(destinationFolder); const file = path.normalize(repoRoot); const stats = fs.statSync(file); if (stats.isFile()) { await extractFiles(file, fileEnding, destinationFolder); const hubDir = path.join( destinationFolder, fs.readdirSync(destinationFolder)[0] ); return hubDir; } else { throw new Error(`file argument ${file} is not a file`); } } async function getDownloadInfo( version: string ): Promise<DownloadInfo> { let platform = ''; let fileExtension = IS_WINDOWS ? '.zip' : '.tar.gz'; if (IS_WINDOWS) { platform = `windows`; } else { if (process.platform === 'darwin') { platform = `darwin`; } else { platform = `linux`; } } if(version){ let validVersion = semver.valid(version); if(!validVersion) { throw new Error( `No valid download found for version ${version}. Check https://github.com/github/hub/releases for a list of valid releases` ); } //specific version, get that version from releases return {url: `https://github.com/github/hub/releases/download/v${version}/hub-${platform}-amd64-${version}${fileExtension}`,version: version} as DownloadInfo; } else{ //get latest release let http: httpm.HttpClient = new httpm.HttpClient('setup-hub'); let releaseJson = await (await http.get('https://api.github.com/repos/github/hub/releases/latest')).readBody(); let releasesInfo = JSON.parse(releaseJson); let latestVersion = releasesInfo.tag_name.substring(1); return {url: `https://github.com/github/hub/releases/latest/download/hub-${platform}-amd64-${latestVersion}${fileExtension}`,version: latestVersion} as DownloadInfo; } } export interface DownloadInfo { url: string; version: string; }
da51b6482bf94c22e835fe9648db4a523279df9e
[ "Markdown", "TypeScript" ]
2
Markdown
Geertvdc/setup-java
e45210d6acdeb82aa7f56e8863128fe2dd7a3563
6f7b26a222af901b676c225b2a57ec0b53571978
refs/heads/master
<file_sep><?php header('Content-type: text/html; charset=utf-8'); require_once ("talesdb.php"); $query = "SELECT*FROM authors"; $select_tales = mysqli_query($link, $query); while ($tales = mysqli_fetch_array($select_tales)){ $img = $tales['img_path']; $suname = $tales['suname']; $book = $tales['book']; $audio_patch = $tales['audio_path']; $ganre = $tales['ganre']; echo "<tr><td>$img</td><td>$name</td><td>$suname</td><td>$book</td><td>$audio_patch</td><td>$ganre</td></tr>"; }; ?> <file_sep>file.reference.Tales-public_html=public_html file.reference.tales-public_html=public_html file.reference.Tales-test=test files.encoding=UTF-8 site.root.folder=${file.reference.tales-public_html}
408fa36d6ae48959bbad3dcb8f75668ca9196e75
[ "PHP", "INI" ]
2
PHP
garibaldi1/tales
57e71e2456c5df7206c71bced990c3a07e07bede
ea5e7d02468071c1937830e713b28942c082341d
refs/heads/master
<repo_name>jbarnesspain/ssec_models<file_sep>/Utils/fine_grained_emotion_dataset.py import csv import numpy as np import sys, os from Utils.Representations import * from Utils.WordVecs import * from Utils.twokenize import * def rem_mentions_urls(tokens): final = [] for t in tokens: if not t.startswith(r'@') and not t.startswith('http'): final.append(t) return final def words(sentence, model): return rem_mentions_urls(tokenize(sentence.lower())) class Fine_Grained_Emotion_Dataset(): def __init__(self, DIR, model, one_hot=True, dtype=np.float32, rep=ave_vecs, threshold=0.0): self.rep = rep self.one_hot = one_hot self.threshold = threshold Xtrain, Xdev, Xtest, ytrain, ydev, ytest = self.open_data(DIR, model, rep) self._Xtrain = Xtrain self._ytrain = ytrain self._Xdev = Xdev self._ydev = ydev self._Xtest = Xtest self._ytest = ytest def open_data(self, DIR, model, rep): Xtrain = [] with open(os.path.join(DIR,'train.csv')) as csv_file: reader = csv.reader(csv_file, delimiter='\t') for i, line in enumerate(reader): # don't get header if i != 0: Xtrain.append(line[0]) Xtest = [] with open(os.path.join(DIR,'test.csv')) as csv_file: reader = csv.reader(csv_file, delimiter='\t') for i, line in enumerate(reader): # don't get header if i != 0: Xtest.append(line[0]) # get Ys Y = [] try: for line in open(os.path.join(DIR, 'vote{0}'.format(self.threshold))): Y.append(np.array(line.split('\t'), dtype=int)) except FileNotFoundError: print('Annotation File not found') Y = np.array(Y) Xtrain = [rep(sent, model) for sent in Xtrain] ytrain = Y[:len(Xtrain)] # ytest = Y[len(Xtrain):] dev_idx = int(len(Xtrain) * .1) Xdev = Xtrain[:dev_idx] ydev = ytrain[:dev_idx] Xtrain = Xtrain[dev_idx:] ytrain = ytrain[dev_idx:] Xtest = [rep(sent, model) for sent in Xtest] assert len(Xtrain) == len(ytrain) assert len(Xdev) == len(Xdev) assert len(Xtest) == len(ytest) if self.rep is not words: Xtrain = np.array(Xtrain) Xdev = np.array(Xdev) Xtest = np.array(Xtest) ytrain = np.array(ytrain) ydev = np.array(ydev) ytest = np.array(ytest) return Xtrain, Xdev, Xtest, ytrain, ydev, ytest <file_sep>/one_vs_all.py from keras.models import Sequential, Model from keras.layers import LSTM, Dropout, Dense, Embedding, Bidirectional, Convolution1D, MaxPooling1D, Flatten, Merge, Input from keras.regularizers import l2 from keras.preprocessing.sequence import pad_sequences import sys import tabulate import argparse import json from Utils.fine_grained_emotion_dataset import * from Utils.MyMetrics import * from Utils.Representations import * from Utils.WordVecs import * from multi_class import * def get_dev_params(model_name, outfile, Xtrain, ytrain, Xdev, ydev, wordvecs, W): # If you have already run the dev experiment, just get results if os.path.isfile(outfile): with open(outfile) as out: dev_results = json.load(out) if model_name in dev_results: f1 = dev_results[model_name]['f1'] dim = dev_results[model_name]['dim'] dropout = dev_results[model_name]['dropout'] epoch = dev_results[model_name]['epoch'] return dim, dropout, epoch, f1 # Otherwise, run a test on the dev set to get the best parameters best_f1 = 0 best_dim = 0 best_dropout = 0 best_epoch = 0 input_dim = W.shape[1] output_dim = ytrain.shape[1] labels = sorted(set(ytrain.argmax(1))) dims = np.arange(50, 300, 25) dropouts = np.arange(0.1, 0.6, 0.1) epochs = np.arange(3, 25) # Do a random search over the parameters for i in range(10): dim = int(dims[np.random.randint(0, len(dims))]) dropout = float(dropouts[np.random.randint(0, len(dropouts))]) epoch = int(epochs[np.random.randint(0, len(epochs))]) if model_name == 'DAN': clf = one_vs_all_classifier('DAN', input_dim=input_dim, dim=dim, out_dim=8, dropout=best_dropout, wordvecs=wordvecs, max_length=Xtrain.shape[1], weights=W, train=True) elif model_name == 'LSTM': clf = one_vs_all_classifier('LSTM', input_dim=input_dim, dim=dim, out_dim=8, dropout=best_dropout, wordvecs=wordvecs, max_length=Xtrain.shape[1], weights=W, train=True) elif model_name == 'BiLSTM': clf = one_vs_all_classifier('BiLSTM', input_dim=input_dim, dim=dim, out_dim=8, dropout=best_dropout, wordvecs=wordvecs, max_length=Xtrain.shape[1], weights=W, train=True) elif model_name == 'CNN': clf = one_vs_all_classifier('CNN', input_dim=input_dim, dim=dim, out_dim=8, dropout=best_dropout, wordvecs=wordvecs, max_length=Xtrain.shape[1], weights=W, train=True) h = clf.fit(Xtrain, ytrain, nb_epoch=epoch, verbose=0) pred = clf.predict(Xdev) if len(labels) == 2: mm = MyMetrics(ydev, pred, one_hot=True, labels=labels, average='binary') _, _, dev_f1 = mm.get_scores() else: mm = MyMetrics(ydev, pred, one_hot=True, labels=labels, average='micro') _, _, dev_f1 = mm.get_scores() if dev_f1 > best_f1: best_f1 = dev_f1 best_dim = dim best_dropout = dropout best_epoch = epoch print('new best f1: {0:.3f} dim:{1} dropout:{2} epochs:{3}'.format(best_f1, dim, dropout, epoch)) if os.path.isfile(outfile): with open(outfile) as out: dev_results = json.load(out) dev_results[model_name] = {'f1': best_f1, 'dim': best_dim, 'dropout': best_dropout, 'epoch': best_epoch} with open(outfile, 'w') as out: json.dump(dev_results, out) else: dev_results = {} dev_results[model_name] = {'f1': best_f1, 'dim': best_dim, 'dropout': best_dropout, 'epoch': best_epoch} with open(outfile, 'w') as out: json.dump(dev_results, out) return best_dim, best_dropout, best_epoch, best_f1 def get_ave_std(pred, y): emo_results = [] for j in range(len(emotions)): emo_y = y[:,j] emo_pred = pred[:,j] mm = MyMetrics(emo_y, emo_pred, one_hot=False, average='binary') acc = mm.accuracy() precision, recall, f1 = mm.get_scores() emo_results.append([acc, precision, recall, f1]) emo_results = np.array(emo_results) return emo_results.mean(axis=0), emo_results.std(axis=0) class one_vs_all_classifier(): """ Creates one classifier per class label and trains to correctly predict that class. """ def __init__(self, model_name, input_dim, dim=100, out_dim=8, dropout=.5, wordvecs=None, max_length=30, weights=None, train=True): self.model_name = model_name self.input_dim = input_dim self.dim = dim self.out_dim = out_dim self.dropout = dropout self.wordvecs = wordvecs self.max_length = max_length self.weights = weights self.train = train self.classifiers = self._setup() def _setup(self): """ create as many classifiers as labels """ classifiers = [] for i in range(self.out_dim): if self.model_name == 'DAN': clf = create_deep(self.input_dim, dim=self.dim, output_dim=1, dropout=self.dropout) elif self.model_name == 'LSTM': clf = create_LSTM(self.wordvecs, self.dim, output_dim=1, dropout=self.dropout, weights = self.weights, train=self.train) elif self.model_name == 'BiLSTM': clf = create_BiLSTM(self.wordvecs, self.dim, output_dim=1, dropout=self.dropout, weights=self.weights, train=self.train) else: clf = create_cnn(self.weights, self.max_length, self.dim, self.dropout, output_dim=1) classifiers.append(clf) return classifiers def fit(self, Xtrain, ytrain, validation_data=None, nb_epoch=10, verbose=1): for i, classifier in enumerate(self.classifiers): h = classifier.fit(Xtrain, ytrain[:,i], validation_data=validation_data, nb_epoch=nb_epoch, verbose=verbose) def predict(self, Xtest): predictions = [] for classifier in self.classifiers: pred = classifier.predict(Xtest) predictions.append(pred) predictions = np.array(predictions) return predictions.reshape((Xtest.shape[0], len(predictions))) def test_embeddings(file, file_type): names = ['DAN', 'LSTM', 'Bi-LSTM'] emotions = ["anger", "anticipation", "disgust", "fear", "joy", "sadness", "surprise", "trust"] # Import dataset where each test example is the words in the tweet dataset = Fine_Grained_Emotion_Dataset('data', None, rep=words) print('Basic statistics') table = [] for i, emo in enumerate(emotions): train = dataset._ytrain[:,i].sum() test = dataset._ytest[:,i].sum() table.append((emo, train, test)) print(tabulate.tabulate(table, headers=['emotion', '#train', '#test'])) print() #### Get Parameters #### max_length = 0 vocab = {} for sent in list(dataset._Xtrain) + list(dataset._Xdev) + list(dataset._Xtest): if len(sent) > max_length: max_length = len(sent) for w in sent: if w not in vocab: vocab[w] = 1 else: vocab[w] += 1 wordvecs = {} print('Importing vectors') for line in open(file): try: split = line.split() word = split[0] vec = np.array(split[1:], dtype='float32') if word in vocab: wordvecs[word] = vec except ValueError: pass dim = len(vec) oov = len(vocab) - len(wordvecs) print('OOV: {0}'.format(oov)) # Add vectors for <unk> add_unknown_words(wordvecs, vocab, min_df=1, dim=dim) W, word_idx_map = get_W(wordvecs, dim=dim) input_dim = W.shape[1] # TODO: change this so I don't have to import vectors I don't need vecs = WordVecs('../comparison_of_sentiment_methods/embeddings/sswe-u-50.txt') vecs._matrix = W vecs._w2idx = word_idx_map vecs.vocab_length, vecs.vector_size = W.shape ave_dataset = Fine_Grained_Emotion_Dataset('data', vecs, rep=ave_vecs) # Get padded word indexes for all X Xtrain = np.array([get_idx_from_sent(' '.join(sent), word_idx_map, max_l=max_length, k=dim) for sent in dataset._Xtrain]) Xdev = np.array([get_idx_from_sent(' '.join(sent), word_idx_map, max_l=max_length, k=dim) for sent in dataset._Xdev]) Xtest = np.array([get_idx_from_sent(' '.join(sent), word_idx_map, max_l=max_length, k=dim) for sent in dataset._Xtest]) #### Test Models #### names = ['DAN', 'LSTM', 'BiLSTM', 'CNN'] # Keep all mean and standard deviations of each emotion over datasets here all_emo_results = [] all_emo_std_devs = [] # Keep all mean and standard deviations of the averaged emotions here averaged_results = [] averaged_std_devs = [] # TEST EACH MODEL for name in names: print('Getting best parameters') dev_params_file = 'dev_params/all_vs_one_best_params.txt' if name == 'DAN': best_dim, best_dropout, best_epoch, best_f1 = get_dev_params(name, dev_params_file, ave_dataset._Xtrain, ave_dataset._ytrain, ave_dataset._Xdev, ave_dataset._ydev, wordvecs, W) else: best_dim, best_dropout, best_epoch, best_f1 = get_dev_params(name, dev_params_file, Xtrain, dataset._ytrain, Xdev, dataset._ydev, wordvecs, W) print('Testing {0}'.format(name)) # Keep the results for the 5 runs over the dataset model_results = [] model_average_results = [] # 5 runs to get average and standard deviation for i, it in enumerate(range(5)): print('Run: {0}'.format(i + 1)) # create and train a new classifier for each iteration if name == 'DAN': model = one_vs_all_classifier('DAN', input_dim=input_dim, dim=best_dim, out_dim=8, dropout=best_dropout, wordvecs=wordvecs, max_length=None, weights=W, train=True) h = model.fit(ave_dataset._Xtrain, ave_dataset._ytrain, nb_epoch=best_epoch, verbose=0) pred = model.predict(ave_dataset._Xtest) # DAN uses different representations than the other models else: if name == 'LSTM': model = one_vs_all_classifier('LSTM', input_dim=input_dim, dim=best_dim, out_dim=8, dropout=best_dropout, wordvecs=wordvecs, max_length=Xtrain.shape[1], weights=W, train=True) elif name == 'BiLSTM': model = one_vs_all_classifier('BiLSTM', input_dim=input_dim, dim=best_dim, out_dim=8, dropout=best_dropout, wordvecs=wordvecs, max_length=Xtrain.shape[1], weights=W, train=True) elif name == 'CNN': model = one_vs_all_classifier('CNN', input_dim=input_dim, dim=best_dim, out_dim=8, dropout=best_dropout, wordvecs=wordvecs, max_length=Xtrain.shape[1], weights=W, train=True) h = model.fit(Xtrain, dataset._ytrain, nb_epoch=best_epoch, verbose=0) pred = model.predict(Xtest) pred = np.array([cutoff(x) for x in pred]) y = dataset._ytest emo_results = [] for j in range(len(emotions)): emo_y = y[:,j] emo_pred = pred[:,j] mm = MyMetrics(emo_y, emo_pred, one_hot=False, average='binary') acc = mm.accuracy() precision, recall, f1 = mm.get_scores() emo_results.append([acc, precision, recall, f1]) emo_results = np.array(emo_results) model_results.append(emo_results) # print('F1 scores') # for emo, result in zip(emotions, emo_results): # a, p, r, f = result # print('{0}: {1:.3f}'.format(emo, f)) ave_acc, ave_prec, ave_rec, mac_f1 = emo_results.mean(axis=0) mic_f1 = micro_f1(dataset._ytest, pred) model_average_results.append((ave_acc,ave_prec, ave_rec, mac_f1, mic_f1)) print('acc: {0:.3f} prec:{1:.3f} rec:{2:.3f} macro-f1:{3:.3f} micro-f1:{4:.3f}'.format(ave_acc, ave_prec, ave_rec, mac_f1, mic_f1)) print() model_results = np.array(model_results) model_average_results = np.array(model_average_results) average_model_results = model_results.mean(axis=0) model_std_dev_results = model_results.std(axis=0) overall_avg = model_average_results.mean(axis=0) overall_std = model_average_results.std(axis=0) all_emo_results.append(average_model_results) all_emo_std_devs.append(model_std_dev_results) averaged_results.append(overall_avg) averaged_std_devs.append(overall_std) return names, all_emo_results, all_emo_std_devs, averaged_results, averaged_std_devs, dim def print_results(file, out_file, file_type): names, all_emo_results, all_emo_std_devs, averaged_results, averaged_std_devs, dim = test_embeddings(file, file_type) emotions = ["anger", "anticipation", "disgust", "fear", "joy", "sadness", "surprise", "trust", "averaged"] if out_file: with open(out_file, 'a') as f: for name, results, std_devs, ave_results, ave_std_dev in zip(names, all_emo_results, all_emo_std_devs, averaged_results, averaged_std_devs): rr = [[u'{0:.3f} \u00B1{1:.3f}'.format(r, s) for r, s in zip(result, std_dev)] for result, std_dev in zip(results, std_devs)] av = [u'{0:.3f} \u00B1{1:.3f}'.format(r, s) for r, s in zip(ave_results, ave_std_dev)] for r in rr: r += ['-'] rr += [av] table = [[emo] + r for emo, r in zip(emotions, rr)] f.write('+++{0}+++\n'.format(name)) f.write(tabulate.tabulate(table, headers=['acc', 'prec', 'rec', 'macro-f1', 'micro-f1'])) f.write('\n') else: for name, results, std_devs, ave_results, ave_std_dev in zip(names, all_emo_results, all_emo_std_devs, averaged_results, averaged_std_devs): rr = [[u'{0:.3f} \u00B1{1:.3f}'.format(r, s) for r, s in zip(result, std_dev)] for result, std_dev in zip(results, std_devs)] av = [u'{0:.3f} \u00B1{1:.3f}'.format(r, s) for r, s in zip(ave_results, ave_std_dev)] for r in rr: r += ['-'] rr += [av] table = [[emo] + r for emo, r in zip(emotions, rr)] print(name) print(tabulate.tabulate(table, headers=['acc', 'prec', 'rec', 'macro-f1', 'micro-f1'])) print() def main(args): parser = argparse.ArgumentParser( description='test embeddings on a suite of datasets') parser.add_argument('-bi', default=False, type=bool) parser.add_argument('-emb', help='location of embeddings', default='../comparison_of_sentiment_methods/embeddings/amazon-sg-50-window10-sample1e-4-negative5.txt') parser.add_argument('-file_type', help='glove style embeddings or word2vec style: default is w2v', default='word2vec') parser.add_argument('-output', help='output file for results', default='./results.txt') parser.add_argument('-printout', help='instead of printing to file, print to sysout', type=bool, default=False) args = vars(parser.parse_args()) embedding_file = args['emb'] file_type = args['file_type'] output = args['output'] printout = args['printout'] print('testing on %s' % embedding_file) if printout: print_results(embedding_file, None, file_type) else: print_results(embedding_file, output, file_type) if __name__ == '__main__': args = sys.argv main(args) <file_sep>/README.md ## Multi-Label Reannotation of the SemEval 2016 Stance Detection Data with Fine-Grained Emotions Code for the paper to-appear. Runs a series of models on the dataset Please cite the original paper when using the data. ### Requirements Code is written in Python (3.5), requires Keras (1) [https://keras.io] and tabulate [https://pypi.python.org/pypi/tabulate]. ### How to use code run ./run.sh from the command line This runs the experiments and produces the latex code for the table containing the neural models, which is saved as /figs/large_table.txt ### Hyperparameters We use a random search to find the best parameters for hidden layers, number of epochs and dropout probability. <file_sep>/one_vs_all_svm.py from multi_class import * from sklearn.svm import LinearSVC import tabulate def dev_parameters(Xtrain, ytrain, Xdev, ydev): best_dev_f1 = 0 best_C = 0 C = [0.001, 0.003, 0.005, 0.007, 0.009, 0.01, 0.03, 0.05, 0.07, 0.09, 0.1, 0.3, 0.5, 0.7, 0.9, 1, 1.5, 1.7, 2] for c in C: ova = one_vs_all(8, C=c) ova.fit(Xtrain, ytrain) pred = ova.predict(Xdev) mic_prec, mic_rec, mic_f1 = micro_f1(ydev, pred) if mic_f1 > best_dev_f1: sys.stdout.write('\rbest dev f1: {0:.1f}'.format(mic_f1 * 100)) best_dev_f1 = mic_f1 best_C = c return best_dev_f1, best_C class one_vs_all(): """ One vs all linear SVM classifiers. """ def __init__(self, output_dim, C=1): self.classifiers = self._setup(output_dim, C=C) def _setup(self, output_dim, C=1): """ Create a separate SVM for each y label. """ classifiers = [] for i in range(output_dim): classifiers.append(LinearSVC(C=C)) return classifiers def fit(self, Xtrain, ytrain): """ input - Xtrain - n x d matrix, n = number of examples, d = feature dimension - ytrain - n x l matrix, l = number of labels the class labels can have more than one positive label for each instance. i.e. [1,0,1,0,1] is acceptable """ for i,classifier in enumerate(self.classifiers): classifier.fit(Xtrain, ytrain[:,i]) def predict(self, X): prediction = [] for classifier in self.classifiers: prediction.append(classifier.predict(X)) return np.array(prediction).T def main(): emotions = ["anger", "anticipation", "disgust", "fear", "joy", "sadness", "surprise", "trust"] vecs = WordVecs('embeddings/twitter_embeddings.txt') dataset = Fine_Grained_Emotion_Dataset('data', None, rep=words) vocab = {} for sent in list(dataset._Xtrain) + list(dataset._Xdev) + list(dataset._Xtest): for w in sent: if w not in vocab: vocab[w] = 1 else: vocab[w] += 1 wordvecs = {} for line in open('embeddings/twitter_embeddings.txt'): try: split = line.split() word = split[0] vec = np.array(split[1:], dtype='float32') if word in vocab: wordvecs[word] = vec except ValueError: pass add_unknown_words(wordvecs, vocab, dim=300) W, word_idx_map = get_W(wordvecs) vecs._matrix = W for threshold in ['0.0', '0.33', '0.5, 0.66', '0.99']: dataset = Fine_Grained_Emotion_Dataset('data', vecs, rep=ave_vecs, threshold=threshold) best_dev_f1, best_C = dev_parameters(dataset._Xtrain, dataset._ytrain, dataset._Xdev, dataset._ydev) ova = one_vs_all(8, C=best_C) ova.fit(dataset._Xtrain, dataset._ytrain) pred = ova.predict(dataset._Xtest) y = dataset._ytest emo_results = [] average_results = [] for j in range(len(emotions)): emo_y = y[:,j] emo_pred = pred[:,j] mm = MyMetrics(emo_y, emo_pred, one_hot=False, average='binary') acc = mm.accuracy() precision, recall, f1 = mm.get_scores() emo_results.append([acc, precision, recall, f1]) emo_results = np.array(emo_results) ave_acc, ave_prec, ave_rec, mac_f1 = emo_results.mean(axis=0) mic_prec, mic_rec, mic_f1 = micro_f1(dataset._ytest, pred) average_results.append([ave_acc, mic_prec, mic_rec, mic_f1]) average_results = np.array(average_results) emo_results *= 100 average_results *= 100 average_results = list(average_results[0]) rr = list([list(x) for x in emo_results]) rr.append(average_results) emotions.append('Micro Avg.') table = [[emo] + r for emo, r in zip(emotions, rr)] print() print(tabulate.tabulate(table, headers=['emotion', 'acc', 'prec', 'rec', 'f1'], floatfmt='.0f')) if __name__ == '__main__': main() <file_sep>/run.sh #!/bin/bash for threshold in 0.0 0.33 0.5 0.66 0.99; do python3 multi_class.py -emb embeddings/twitter_embeddings.txt -threshold $threshold -output results/results_$threshold done python3 Utils/create_large_table.py -results_dir results -outfile fig/large_table.txt<file_sep>/multi_class.py from keras.models import Sequential, Model from keras.layers import LSTM, Dropout, Dense, Embedding, Bidirectional, Convolution1D, MaxPooling1D, Flatten, Merge, Input from keras.regularizers import l2 from keras.preprocessing.sequence import pad_sequences import sys import tabulate import argparse import json from Utils.fine_grained_emotion_dataset import * from Utils.MyMetrics import * from Utils.Representations import * from Utils.WordVecs import * def get_dev_params(model_name, outfile, Xtrain, ytrain, Xdev, ydev, wordvecs, W): # If you have already run the dev experiment, just get results if os.path.isfile(outfile): with open(outfile) as out: dev_results = json.load(out) if model_name in dev_results: f1 = dev_results[model_name]['f1'] dim = dev_results[model_name]['dim'] dropout = dev_results[model_name]['dropout'] epoch = dev_results[model_name]['epoch'] return dim, dropout, epoch, f1 # Otherwise, run a test on the dev set to get the best parameters best_f1 = 0 best_dim = 0 best_dropout = 0 best_epoch = 0 output_dim = ytrain.shape[1] labels = sorted(set(ytrain.argmax(1))) dims = np.arange(50, 300, 25) dropouts = np.arange(0.1, 0.6, 0.1) epochs = np.arange(3, 25) # Do a random search over the parameters for i in range(10): dim = int(dims[np.random.randint(0, len(dims))]) dropout = float(dropouts[np.random.randint(0, len(dropouts))]) epoch = int(epochs[np.random.randint(0, len(epochs))]) if model_name == 'DAN': clf = create_deep(input_dim=len(W[0]), num_hidden_layers=3, dim=dim, output_dim=ytrain.shape[1], dropout=dropout) elif model_name == 'LSTM': clf = create_LSTM(wordvecs, dim=dim, output_dim=8, dropout=dropout, weights=W, train=True) elif model_name == 'BiLSTM': clf = create_BiLSTM(wordvecs, dim=dim, output_dim=8, dropout=dropout, weights=W, train=True) elif model_name == 'CNN': clf = create_cnn(W, Xtrain.shape[1], dim=dim, dropout=dropout) h = clf.fit(Xtrain, ytrain, nb_epoch=epoch, verbose=0) pred = clf.predict(Xdev, verbose=0) if len(labels) == 2: mm = MyMetrics(ydev, pred, one_hot=True, labels=labels, average='binary') _, _, dev_f1 = mm.get_scores() else: mm = MyMetrics(ydev, pred, one_hot=True, labels=labels, average='micro') _, _, dev_f1 = mm.get_scores() if dev_f1 > best_f1: best_f1 = dev_f1 best_dim = dim best_dropout = dropout best_epoch = epoch print('new best f1: {0:.3f} dim:{1} dropout:{2} epochs:{3}'.format(best_f1, dim, dropout, epoch)) if os.path.isfile(outfile): with open(outfile) as out: dev_results = json.load(out) dev_results[model_name] = {'f1': best_f1, 'dim': best_dim, 'dropout': best_dropout, 'epoch': best_epoch} with open(outfile, 'w') as out: json.dump(dev_results, out) else: dev_results = {} dev_results[model_name] = {'f1': best_f1, 'dim': best_dim, 'dropout': best_dropout, 'epoch': best_epoch} with open(outfile, 'w') as out: json.dump(dev_results, out) return best_dim, best_dropout, best_epoch, best_f1 def macro_f1(y, pred): precisions, recalls = [], [] num_labels = y.shape[1] for emo in range(num_labels): tp = 0 fp = 0 fn = 0 for i, j in enumerate(y[:,emo]): if j == 1 and pred[:,emo][i] == 1: tp += 1 elif j == 1 and pred[:,emo][i] == 0: fn += 1 elif j == 0 and pred[:,emo][i] == 1: fp += 1 try: pr = tp / (tp + fp) except ZeroDivisionError: pr = 0 try: rc = tp / (tp + fn) except ZeroDivisionError: rc = 0 precisions.append(pr) recalls.append(rc) precisions = np.array(precisions) recalls = np.array(precisions) macro_precision = precisions.mean() macro_recall = recalls.mean() macro_f1 = 2 * ((macro_precision * macro_recall) / (macro_precision + macro_recall)) return macro_f1 def micro_f1(y, pred): true_pos, false_pos, false_neg = [], [], [] num_labels = y.shape[1] for emo in range(num_labels): tp = 0 fp = 0 fn = 0 for i, j in enumerate(y[:,emo]): if j == 1 and pred[:,emo][i] == 1: tp += 1 elif j == 1 and pred[:,emo][i] == 0: fn += 1 elif j == 0 and pred[:,emo][i] == 1: fp += 1 true_pos.append(tp) false_pos.append(fp) false_neg.append(fn) true_pos = np.array(true_pos) false_pos = np.array(false_pos) false_neg = np.array(false_neg) micro_precision = true_pos.sum() / (true_pos.sum() + false_pos.sum()) micro_recall = true_pos.sum() / (true_pos.sum() + false_neg.sum()) micro_f1 = 2 * ((micro_precision * micro_recall) / (micro_precision + micro_recall)) return micro_precision, micro_recall, micro_f1 def get_idx_from_sent(sent, word_idx_map, max_l=50, k=50, filter_h=5): """ Transforms sentence into a list of indices, padded with zeros. """ x = [] pad = filter_h-1 for i in range(pad): x.append(0) words = sent.split() for word in words: if word in word_idx_map: x.append(word_idx_map[word]) while len(x) < max_l + 2 * pad: x.append(0) return x def add_unknown_words(wordvecs, vocab, min_df=1, dim=50): """ For words that occur at least min_df, create a separate word vector 0.25 is chosen so the unk vectors have approximately the same variance as pretrained ones """ for word in vocab: if word not in wordvecs and vocab[word] >= min_df: wordvecs[word] = np.random.uniform(-0.25, 0.25, dim) def get_W(wordvecs, dim=300): """ Get word matrix. W[i] is the vector for word indexed by i """ vocab_size = len(wordvecs) word_idx_map = dict() W = np.zeros(shape=(vocab_size+1, dim), dtype='float32') W[0] = np.zeros(dim, dtype='float32') i = 1 for word in wordvecs: W[i] = wordvecs[word] word_idx_map[word] = i i += 1 return W, word_idx_map def create_LSTM(wordvecs, dim=300, output_dim=8, dropout=.5, weights=None, train=True): model = Sequential() model.add(Embedding(weights.shape[0], weights.shape[1], weights=[weights], trainable=train)) model.add(Dropout(dropout)) model.add(LSTM(dim)) #model.add(LSTM(dim, W_regularizer=l2())) model.add(Dropout(dropout)) model.add(Dense(50, activation='relu')) model.add(Dense(output_dim, activation='sigmoid')) model.compile('adam', 'binary_crossentropy', metrics=['accuracy']) return model def create_BiLSTM(wordvecs, dim=300, output_dim=8, dropout=.5, weights=None, train=True): model = Sequential() model.add(Embedding(weights.shape[0], weights.shape[1], weights=[weights], trainable=train)) model.add(Dropout(dropout)) model.add(Bidirectional(LSTM(dim))) #model.add(Bidirectional(LSTM(dim, regularizer=l2()))) model.add(Dropout(dropout)) model.add(Dense(50, activation='relu')) model.add(Dense(output_dim, activation='sigmoid')) model.compile('adam', 'binary_crossentropy', metrics=['accuracy']) return model def create_cnn(W, max_length, dim=300, dropout=.5, output_dim=8): # Convolutional model filter_sizes=(2,3,4) num_filters = 3 hidden_dim=100 graph_in = Input(shape=(max_length, len(W[0]))) convs = [] for fsz in filter_sizes: conv = Convolution1D(nb_filter=num_filters, filter_length=fsz, border_mode='valid', activation='relu', subsample_length=1)(graph_in) pool = MaxPooling1D(pool_length=2)(conv) flatten = Flatten()(pool) convs.append(flatten) out = Merge(mode='concat')(convs) graph = Model(input=graph_in, output=out) # Full model model = Sequential() model.add(Embedding(output_dim=W.shape[1], input_dim=W.shape[0], input_length=max_length, weights=[W], trainable=True)) model.add(Dropout(dropout)) model.add(graph) model.add(Dense(dim, activation='relu')) model.add(Dropout(dropout)) model.add(Dense(output_dim, activation='sigmoid')) model.compile('adam', 'binary_crossentropy', metrics=['accuracy']) return model def cutoff(x, c=.5): """ Decide where the cutoff for probability is for predicting a positive class. """ z = [] for i in x: if i > c: z.append(1) else: z.append(0) return np.array(z) def pad_dataset(dataset, maxlen=50): dataset._Xtrain = pad_sequences(dataset._Xtrain, maxlen) dataset._Xdev = pad_sequences(dataset._Xdev, maxlen) dataset._Xtest = pad_sequences(dataset._Xtest, maxlen) def write_vecs(matrix, w2idx, outfile): vocab = sorted(w2idx.keys()) with open(outfile, 'w') as out: for w in vocab: try: out.write(w + ' ') v = matrix[w2idx[w]] for j in v: out.write('{0:.7}'.format(j)) out.write('\n') except UnicodeEncodeError: pass def test_embeddings(file, threshold, file_type): emotions = ["anger", "anticipation", "disgust", "fear", "joy", "sadness", "surprise", "trust"] # Import dataset where each test example is the words in the tweet dataset = Fine_Grained_Emotion_Dataset('data', None, rep=words, threshold=threshold) print('Basic statistics') table = [] for i, emo in enumerate(emotions): train = dataset._ytrain[:,i].sum() test = dataset._ytest[:,i].sum() table.append((emo, train, test)) print(tabulate.tabulate(table, headers=['emotion', '#train', '#test'])) #### Get Parameters #### max_length = 0 vocab = {} for sent in list(dataset._Xtrain) + list(dataset._Xdev) + list(dataset._Xtest): if len(sent) > max_length: max_length = len(sent) for w in sent: if w not in vocab: vocab[w] = 1 else: vocab[w] += 1 wordvecs = {} print('Importing vectors') for line in open(file): try: split = line.split() word = split[0] vec = np.array(split[1:], dtype='float32') if word in vocab: wordvecs[word] = vec except ValueError: pass dim = len(vec) oov = len(vocab) - len(wordvecs) print('OOV: {0}'.format(oov)) # Add vectors for <unk> add_unknown_words(wordvecs, vocab, min_df=1, dim=dim) W, word_idx_map = get_W(wordvecs, dim=dim) # TODO: change this so I don't have to import vectors I don't need vecs = WordVecs(file) vecs._matrix = W vecs._w2idx = word_idx_map vecs.vocab_length, vecs.vector_size = W.shape ave_dataset = Fine_Grained_Emotion_Dataset('data', vecs, rep=ave_vecs) # Get padded word indexes for all X Xtrain = np.array([get_idx_from_sent(' '.join(sent), word_idx_map, max_l=max_length, k=dim) for sent in dataset._Xtrain]) Xdev = np.array([get_idx_from_sent(' '.join(sent), word_idx_map, max_l=max_length, k=dim) for sent in dataset._Xdev]) Xtest = np.array([get_idx_from_sent(' '.join(sent), word_idx_map, max_l=max_length, k=dim) for sent in dataset._Xtest]) #### Test Models #### names = ['LSTM', 'BiLSTM', 'CNN'] # Keep all mean and standard deviations of each emotion over datasets here all_emo_results = [] all_emo_std_devs = [] # Keep all mean and standard deviations of the averaged emotions here averaged_results = [] averaged_std_devs = [] # TEST EACH MODEL for name in names: print('Getting best parameters') dev_params_file = 'dev_params/'+str(W.shape[1])+'_params.txt' best_dim, best_dropout, best_epoch, best_f1 = get_dev_params(name, dev_params_file, Xtrain, dataset._ytrain, Xdev, dataset._ydev, wordvecs, W) print('Testing {0}'.format(name)) # Keep the results for the 5 runs over the dataset model_results = [] model_average_results = [] # 5 runs to get average and standard deviation for i, it in enumerate(range(5)): print('Run: {0}'.format(i + 1)) # create and train a new classifier for each iteration if name == 'LSTM': model = create_LSTM(wordvecs, dim=best_dim, output_dim=8, dropout=best_dropout, weights=W, train=True) elif name == 'BiLSTM': model = create_BiLSTM(wordvecs, dim=best_dim, output_dim=8, dropout=best_dropout, weights=W, train=True) elif name == 'CNN': model = create_cnn(W, Xtrain.shape[1]) h = model.fit(Xtrain, dataset._ytrain, validation_data=[Xdev, dataset._ydev], nb_epoch=best_epoch, verbose=0) pred = model.predict(Xtest) pred = np.array([cutoff(x) for x in pred]) y = dataset._ytest emo_results = [] for j in range(len(emotions)): emo_y = y[:,j] emo_pred = pred[:,j] mm = MyMetrics(emo_y, emo_pred, one_hot=False, average='binary') acc = mm.accuracy() precision, recall, f1 = mm.get_scores() emo_results.append([acc, precision, recall, f1]) emo_results = np.array(emo_results) model_results.append(emo_results) # print('F1 scores') # for emo, result in zip(emotions, emo_results): # a, p, r, f = result # print('{0}: {1:.3f}'.format(emo, f)) ave_acc, ave_prec, ave_rec, mac_f1 = emo_results.mean(axis=0) mic_prec, mic_rec, mic_f1 = micro_f1(dataset._ytest, pred) model_average_results.append((ave_acc, mic_prec, mic_rec, mic_f1)) print('acc: {0:.3f} micro-prec:{1:.3f} micro-rec:{2:.3f} micro-f1:{3:.3f}'.format(ave_acc, mic_prec, mic_rec, mic_f1)) print() model_results = np.array(model_results) model_average_results = np.array(model_average_results) average_model_results = model_results.mean(axis=0) model_std_dev_results = model_results.std(axis=0) overall_avg = model_average_results.mean(axis=0) overall_std = model_average_results.std(axis=0) all_emo_results.append(average_model_results) all_emo_std_devs.append(model_std_dev_results) averaged_results.append(overall_avg) averaged_std_devs.append(overall_std) return names, all_emo_results, all_emo_std_devs, averaged_results, averaged_std_devs, dim def print_results(file, out_file, threshold, file_type): names, all_emo_results, all_emo_std_devs, averaged_results, averaged_std_devs, dim = test_embeddings(file, threshold, file_type) emotions = ["anger", "anticipation", "disgust", "fear", "joy", "sadness", "surprise", "trust", "micro-averaged"] if out_file: with open(out_file, 'a') as f: for name, results, std_devs, ave_results, ave_std_dev in zip(names, all_emo_results, all_emo_std_devs, averaged_results, averaged_std_devs): rr = [[u'{0:.3f} \u00B1{1:.3f}'.format(r, s) for r, s in zip(result, std_dev)] for result, std_dev in zip(results, std_devs)] av = [u'{0:.3f} \u00B1{1:.3f}'.format(r, s) for r, s in zip(ave_results, ave_std_dev)] rr += [av] table = [[emo] + r for emo, r in zip(emotions, rr)] f.write('+++{0}+++\n'.format(name)) f.write(tabulate.tabulate(table, headers=['acc', 'prec', 'rec', 'f1'])) f.write('\n') else: for name, results, std_devs, ave_results, ave_std_dev in zip(names, all_emo_results, all_emo_std_devs, averaged_results, averaged_std_devs): rr = [[u'{0:.3f} \u00B1{1:.3f}'.format(r, s) for r, s in zip(result, std_dev)] for result, std_dev in zip(results, std_devs)] av = [u'{0:.3f} \u00B1{1:.3f}'.format(r, s) for r, s in zip(ave_results, ave_std_dev)] rr += [av] table = [[emo] + r for emo, r in zip(emotions, rr)] print(name) print(tabulate.tabulate(table, headers=['acc', 'prec', 'rec', 'f1'])) print() def main(args): parser = argparse.ArgumentParser( description='test embeddings on a suite of datasets') parser.add_argument('-bi', default=False, type=bool) parser.add_argument('-emb', help='location of embeddings', default='../comparison_of_sentiment_methods/embeddings/amazon-sg-50-window10-sample1e-4-negative5.txt') parser.add_argument('-threshold', default='0.0', type=str) parser.add_argument('-file_type', help='glove style embeddings or word2vec style: default is w2v', default='word2vec') parser.add_argument('-output', help='output file for results', default='./results.txt') parser.add_argument('-printout', help='instead of printing to file, print to sysout', type=bool, default=False) args = vars(parser.parse_args()) embedding_file = args['emb'] threshold = args['threshold'] file_type = args['file_type'] output = args['output'] printout = args['printout'] print('testing on %s' % embedding_file) if printout: print_results(embedding_file, None, threshold, file_type) else: print_results(embedding_file, output, threshold, file_type) if __name__ == '__main__': args = sys.argv main(args) <file_sep>/Utils/create_large_table.py import sys, os import argparse import numpy as np def main(args): parser = argparse.ArgumentParser(description='create results table for deep learning models') parser.add_argument('-results_dir', help='''location of results file from multi_class.py or one_vs_all.py''') parser.add_argument('-outfile', default=None) args = vars(parser.parse_args()) results_dir = args['results_dir'] outfile = args['outfile'] table_header = """\\begin{table*}[t] \\resizebox{\\textwidth}{!}{ \centering \\renewcommand*{\\arraystretch}{0.9} \setlength\\tabcolsep{1.8mm} \\begin{tabular}{l|lrrrrrrrrrrrrrrr} \\toprule \multicolumn{2}{c}{} & \multicolumn{15}{c}{Results for Treshold} \\\\ \cmidrule(l){3-17} \multicolumn{2}{c}{} & \multicolumn{3}{c}{0.0} & \multicolumn{3}{c}{0.33} & \multicolumn{3}{c}{0.5} & \multicolumn{3}{c}{0.66} & \multicolumn{3}{c}{0.99} \\\\ \cmidrule(r){2-2}\cmidrule(rl){3-5}\cmidrule(rl){6-8}\cmidrule(rl){9-11}\cmidrule(rl){12-14}\cmidrule(rl){15-17} \multicolumn{1}{c}{} & Emotion & P & R & \F & P & R & \F & P & R & \F & P & R & \F & P & R & \F \\\\ """ table_footer = """ \cmidrule(r){2-2}\cmidrule(rl){3-5}\cmidrule(rl){6-8}\cmidrule(rl){9-11}\cmidrule(rl){12-14}\cmidrule(rl){15-17} \\bottomrule \end{tabular} } \caption{Results of non-linear models for labels of different thresholds. We report the mean precision, recall and f1 for each emotion over 5 runs (standard deviations are included in parenthesis).} \label{tab:resultsdeepthresholds} \end{table*} """ model_header = """ \cmidrule(r){1-2}\cmidrule(rl){3-5}\cmidrule(rl){6-8}\cmidrule(rl){9-11}\cmidrule(rl){12-14}\cmidrule(rl){15-17} \multirow{9}{*}{\\rt{""" model_header2 = """}}\n""" model_outer = """ \cmidrule(r){2-2}\cmidrule(rl){3-5}\cmidrule(rl){6-8}\cmidrule(rl){9-11}\cmidrule(rl){12-14}\cmidrule(rl){15-17}\n""" emo_fmt = ' & {0}& {1:.0f} ({2:.1f}) & {3:.0f} ({4:.1f}) & {5:.0f} ({6:.1f}) & {7:.0f} ({8:.1f}) & {9:.0f} ({10:.1f}) & {11:.0f} ({12:.1f}) & {13:.0f} ({14:.1f}) & {15:.0f} ({16:.1f}) & {17:.0f} ({18:.1f}) & {19:.0f} ({20:.1f}) & {21:.0f} ({22:.1f}) & {23:.0f} ({24:.1f}) & {25:.0f} ({26:.1f}) & {27:.0f} ({28:.1f}) & {29:.0f} ({30:.1f}) \\\\' emotions = ['Anger', 'Anticipation', 'Disgust', 'Fear', 'Joy', 'Sadness', 'Surprise', 'Trust', 'Micro-Avg.'] results_txts = ['results_0.0.txt', 'results_0.33.txt', 'results_0.5.txt', 'results_0.66.txt', 'results_0.99.txt'] results_files = [os.path.join(results_dir, f) for f in results_txts] files = [open(f).readlines() for f in results_files] if outfile: with open(outfile, 'a') as out: out.write(table_header + '\n') for i, l in enumerate(files[0]): if l.startswith('+++'): name = l.strip().replace('+','') results = [file[i+3:i+12] for file in files] results = [[l.replace('±', '').split()[3:] for l in result] for result in results] results = [[np.array(l, dtype=float) * 100 for l in result] for result in results] results = np.concatenate(results, axis=1) out.write(model_header + name + model_header2) for j, r in enumerate(results): if j != 8: towrite = [emotions[j]] + list(r) out.write(emo_fmt.format(*towrite) + '\n') else: towrite = [emotions[j]] + list(r) out.write(model_outer) out.write(emo_fmt.format(*towrite) + '\n') out.write('\n') out.write(table_footer) else: for i, l in enumerate(files[0]): if l.startswith('+++'): name = l.strip().replace('+','') results = [file[i+3:i+12] for file in files] results = [[l.replace('±', '').split()[3:] for l in result] for result in results] results = [[np.array(l, dtype=float) * 100 for l in result] for result in results] results = np.concatenate(results, axis=1) print(name) for j, r in enumerate(results): towrite = [emotions[j]] + list(r) print(emo_fmt.format(*towrite)) print() print() if __name__ == '__main__': args = sys.argv main(args)
4062ae99a72932e771d60094d4b528636ae51dba
[ "Markdown", "Python", "Shell" ]
7
Python
jbarnesspain/ssec_models
59f67c94655d2599da508ed4161a1e05410f04fd
657df09d7a304955634e52bbc9ae5178696dfd93
refs/heads/master
<repo_name>ddWayontec/CSPC_501_A1<file_sep>/src/main/javafiles/Customer.java package main.javafiles; public class Customer { String fName; String lName; String address; String postalCode; String phoneNumber; String email; String gender; int customerId; int creditCardScore; Account chequings = null; Account savings = null; Account investment = null; public Customer(int customerId, String fName, String lName, String address, String postalCode, String phoneNumber, String email, String gender, int creditCardScore) { this.customerId = customerId; this.fName = fName; this.lName = lName; this.address = address; this.postalCode = postalCode; this.phoneNumber = phoneNumber; this.email = email; this.gender = gender; this.creditCardScore = creditCardScore; } public double accountsTotal() { double total = 0; if (chequings != null) { total += chequings.getBalance(); } if (savings != null) { total += savings.getBalance(); } if (investment != null) { total += investment.getBalance(); } return total; } public Account createChequings(double balance, int accountNumber, String homeBranch) { if (chequings == null) { chequings = new Chequings(balance, accountNumber, homeBranch, this); } return chequings; } public Account getChequings() { return this.chequings; } public Account createSavings(double balance, int accountNumber, String homeBranch) { if ( savings == null) { savings = new Savings(balance, accountNumber, homeBranch, this); } return savings; } public Account getSavings() { return this.savings; } public Account createInvestment(double balance, int accountNumber, String homeBranch, RiskLevel riskLevel) { if (investment == null) { investment = new Investment(accountNumber, homeBranch, balance, riskLevel); } return investment; } public Account getInvestment() { return this.investment; } public void setCustomerId(int customerId) { this.customerId = customerId; } public int getCustomerId() { return customerId; } public void setfName(String fName) { this.fName = fName; } public String getfName() { return fName; } public void setlName(String lName) { this.lName = lName; } public String getlName() { return lName; } public void setAddress(String address) { this.address = address; } public String getAddress() { return address; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getPostalCode() { return postalCode; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getPhoneNumber() { return phoneNumber; } public void setEmail(String email) { this.email = email; } public String getEmail() { return email; } public void setGender(String gender) { this.gender = gender; } public String getGender() { return gender; } public void setCreditCardScore(int creditCardScore) { this.creditCardScore = creditCardScore; } public int getCreditCardScore() { return creditCardScore; } } <file_sep>/src/main/javafiles/Investment.java package main.javafiles; import java.util.Random; public class Investment extends Account { double interestRate; public Investment(int accountNumber, String homeBranch, double initialDeposit, RiskLevel riskLevel) { this.accountNumber = accountNumber; this.homeBranch = homeBranch; this.balance = initialDeposit; setInterestRateBasedOnRiskLevel(riskLevel); } public void applyInterestRate() { //remove investmentCalculator.java and move methods to here double interestApplied = calculateInterestApplied(getBalance(), getInterestRate()); depositFunds(interestApplied); } public void setInterestRateBasedOnRiskLevel(RiskLevel riskLevel) { if (riskLevel == RiskLevel.High) { this.interestRate = calculateHighRiskInterestRate(); } else if (riskLevel == RiskLevel.Medium) { this.interestRate = calculateMediumRiskInterestRate(); } else if (riskLevel == RiskLevel.Low) { this.interestRate = calculateLowRiskInterestRate(); } } public double getInterestRate() { return interestRate; } public double calculateInterestApplied(double balance, double interestRate) { return (balance * interestRate); } public double calculateLowRiskInterestRate() { Random randomNum = new Random(); return (randomNum.nextDouble() - 0.5) * 5; } public double calculateMediumRiskInterestRate() { Random randomNum = new Random(); return (randomNum.nextDouble() - 0.5) * 10; } public double calculateHighRiskInterestRate() { Random randomNum = new Random(); return (randomNum.nextDouble() - 0.5) * 20; } } <file_sep>/src/main/javafiles/Chequings.java package main.javafiles; public class Chequings extends Account { public Chequings(double balance, int accountNumber, String homeBranch, Customer customer) { this.balance = balance; this.accountNumber = accountNumber; this.homeBranch = homeBranch; this.customer = customer; } public void makePurchase(double amount) { if (amount <= getBalance()) this.balance = this.balance - amount; } } <file_sep>/README.md # CSPC_501_A1
f696eaa6974f22babf051e84f6b24e4ca9e33ecf
[ "Markdown", "Java" ]
4
Java
ddWayontec/CSPC_501_A1
36474ea033949480dc2fb04c103f10487c5d10ca
0483c46c0c32dd47af1a8a0b6aff0814cb527c47
refs/heads/master
<file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-24 13:44 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('votos', '0001_initial'), ] operations = [ migrations.AddField( model_name='votos', name='candidatov', field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='votos.Candidato'), preserve_default=False, ), migrations.AddField( model_name='votos', name='distritov', field=models.ForeignKey(default=2, on_delete=django.db.models.deletion.CASCADE, to='votos.Distrito'), preserve_default=False, ), migrations.AlterField( model_name='candidato', name='edadc', field=models.IntegerField(default='0'), ), migrations.AlterField( model_name='candidato', name='nombrec', field=models.CharField(default='Nombre canditdato', max_length=50), ), ] <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import Distrito from .models import Candidato from .models import Votos # TODO Register your models here. admin.site.register(Distrito) admin.site.register(Candidato) admin.site.register(Votos)<file_sep># -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2017-11-24 13:53 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('votos', '0002_auto_20171124_1344'), ] operations = [ migrations.AlterField( model_name='candidato', name='nombrec', field=models.CharField(default='Nombre candidato', max_length=50), ), ] <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class Distrito(models.Model): """ Se decide utilizar este modelo para la clase distrito porque es necesario el nombre y la cantidad de votantes, y en un futuro se mostrara un mapa con un marker por cada distrito que contenga los resultados del mismo. """ nombre = models.CharField('Nombre del distrito', max_length=128) cantidad_votantes = models.IntegerField('Cantidad de votantes', default=0) latitude = models.DecimalField('Latitud', max_digits=14, decimal_places=10, default=0) longitude = models.DecimalField('Latitud', max_digits=14, decimal_places=10, default=0) def __str__(self): return 'Distrito {}'.format(self.nombre) class Candidato(models.Model): """ Cree variable nombre con un maximo de 50 caracteres , con valor por default Nombre candidato, y ademas tiene edad con valor por default 0 """ nombrec = models.CharField(max_length=50, default='Nombre candidato') edadc = models.IntegerField(default='0') #esta funcion define el nombre del objeto que aparecera en el admin def __str__(self): return 'Candidato {}'.format(self.nombrec) class Votos(models.Model): """ Aca cree dos foreign Keys para definir que el voto contiene un candidato y un distrito. """ candidatov = models.ForeignKey(Candidato) voto = models.IntegerField(null=True) distritov = models.ForeignKey(Distrito) def __str__(self): return 'voto para {}'.format(self.candidatov)
76cca9ff52b50866f235aaf03e1608666def76b8
[ "Python" ]
4
Python
inakipinke/EF6C2017
b5e1064909c103a5982ab362c3e9b39536d453c1
69577f7473d684da56bef5adee10bfe2c850e7d9
refs/heads/master
<file_sep># Emulation-of-distributed-airline-ticket-reservation-system Developed as a mini project to emulate a distributed client server ticket reservation sysytem. <br>Pyhton (3.6) socket programming used to create multiple sockets as servers and clients. <br>Run MainServer.py <br>airlineServer1.py <br>airlineClient1.py <br>airlineServer2.py <br>airlineClient2.py in the order to understand the distributed running reservation system. <file_sep>import socket import threading import pickle #two sockets for connecting to main server and accepting client connections s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 10000)) s2.bind(('127.0.0.1', 10001)) s.send(bytes('Server', 'utf-8')) flightMatrix = s.recv(1024) flightMatrix = pickle.loads(flightMatrix) flightLocation = s.recv(1024) flightLocation = pickle.loads(flightLocation) def Main(): print('Chart Update:') print(flightMatrix) while True: s2.listen(1) c, addr = s2.accept() t1 = threading.Thread(target = reserve, args = (c,addr)) t1.daemon = True t1.start() t2 = threading.Thread(target = update, args = (s,)) t2.daemon = True t2.start() def reserve(c, a): global flightMatrix while True: c.send(bytes('Location Availability\n1.Pune\n2.Cochin\n3.Mumbai\n4.Chennai\n5.Kolkata\n(source number,destination number,number of seats):-', 'utf-8')) request = c.recv(1024) request = str(request, 'utf-8') request = request.split(',') c.send(bytes('Tickets available from '+flightLocation[int(request[0])]+' to '+flightLocation[int(request[1])]+' : '+str(flightMatrix[int(request[0])-1][int(request[1])-1]), 'utf-8')) if (flightMatrix[int(request[0])-1][int(request[1])-1] >= int(request[2])): flightMatrix[int(request[0])-1][int(request[1])-1] = flightMatrix[int(request[0])-1][int(request[1])-1] - int(request[2]) c.send(bytes('Your tickets from '+flightLocation[int(request[0])]+' to '+flightLocation[int(request[1])]+' are booked', 'utf-8')) print('Chart Update:') print(flightMatrix) flightMatrix2 = pickle.dumps(flightMatrix) s.send(flightMatrix2) else: c.send(bytes('Tickets not available', 'utf-8')) c.send(bytes('Do you want to continue(y/n):', 'utf-8')) choice = c.recv(1024) choice = str(choice, 'utf-8') if choice == 'n': c.send(bytes('Thank You.', 'utf-8')) c.close break def update(s): global flightMatrix while True: flightMatrix = s.recv(1024) flightMatrix = pickle.loads(flightMatrix) if __name__ == '__main__': Main() <file_sep>import socket import threading import numpy as np import pickle s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #matrix of ticket availability flightMatrix = np.array([[0,12,9,3,0], [10,0,20,7,4], [9,11,0,5,3], [30,2,15,0,8], [0,8,13,20,0]]) flightMatrix = np.reshape(flightMatrix,(5,5)) flightLocation = {1:'Pune', 2:'Cochin', 3:'Mumbai', 4:'Chennai', 5:'Kolkata'} #available server list for clients to connect to servers = [10001,10002,10003] connections = [] s.bind(('127.0.0.1', 10000)) def Main(): while True: print("Main Server Running") s.listen(1) c, addr = s.accept() typeofConn = c.recv(1024) if not typeofConn: break; #check to find whther incoming connection is a client or a server if str(typeofConn,'utf-8') == 'Client': c.send(bytes('Welcome to LightSpeed Airlines', 'utf-8')) server2 = pickle.dumps(servers) c.send(server2) if str(typeofConn,'utf-8') == 'Server': connections.append(c) flightMatrix2 = pickle.dumps(flightMatrix) c.send(flightMatrix2) flightLocation2 = pickle.dumps(flightLocation) c.send(flightLocation2) #thread for continous update of flightmatrix from various servers t1 = threading.Thread(target = update, args = (c,addr)) t1.daemon = True t1.start() print("Main Server Stopped") def update(c,addr): global flightMatrix while True: data = c.recv(1024) if not data: break; flightMatrix = pickle.loads(data) #send update to all servers for connection in connections: flightMatrix2 = pickle.dumps(flightMatrix) connection.send(flightMatrix2) if __name__ == '__main__': Main()<file_sep>import socket import threading import pickle s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 10000)) def Main(): while True: s.send(bytes('Client', 'utf-8')) data = s.recv(1024) print(str(data,'utf-8')) if not data: break data = s.recv(1024) servers = pickle.loads(data) #first server ignored just so this client connects to the second server for emulating multiple server client communications try: s2.connect(('127.0.0.1',servers[1])) except: try: s2.connect(('127.0.0.1',servers[1])) except: try: s2.connect(('127.0.0.1',servers[2])) except: print("All servers are down") finally: t2 = threading.Thread(target = sendMsg) t2.daemon = True t2.start() while True: data = s2.recv(1024) if not data: break print(str(data, 'utf-8')) def sendMsg(): while True: s2.send(bytes(input(''), 'utf-8')) if __name__ == '__main__': Main()
9d875b899abcc99e28beda1555c74cad3ab952ee
[ "Markdown", "Python" ]
4
Markdown
aravindrenjan/Emulation-of-distributed-airline-ticket-reservation-system
4d4a4a8893958b55f621427dbe1e9fedc3666af1
d2fb999b6bca5f2bee274f3424f8b916708bb4ac
refs/heads/main
<file_sep> #include <iostream> #include <string> #include <cassert> //1. Создать абстрактный класс Figure(фигура).Его наследниками являются классы Parallelogram(параллелограмм) и Circle(круг). //Класс Parallelogram — базовый для классов Rectangle(прямоугольник), Square(квадрат), Rhombus(ромб).Для всех классов создать конструкторы. //Для класса Figure добавить чисто виртуальную функцию area() (площадь).Во всех остальных классах переопределить эту функцию, //исходя из геометрических формул нахождения площади. class Figure { public: Figure() { }; virtual double area() = 0; virtual ~Figure() { }; }; class Circle : public Figure { private: double m_radius = 0; public: Circle() { }; Circle(double m_radius) : m_radius(m_radius) {}; void setRadius(double radius) { m_radius = radius; } double area () override { return m_radius * m_radius * 3.14; // Число Пи, точность достаточна для теста, я думаю. } ~Circle() { }; }; class Parallelogram : public Figure { protected: double m_height = 0; // высота double m_lenght = 0; // длина основания public: Parallelogram() {}; void setHeight(double height) { m_height = height; } void setLenght(double lenght) { m_lenght = lenght; } double area() { return m_height * m_lenght; }; ~Parallelogram() {}; }; class Rectangle : public Parallelogram { public: Rectangle() {}; double area() { return m_height * m_lenght; }; ~Rectangle() {}; }; class Square : public Parallelogram { public: Square() {}; double area() { return m_height * m_lenght; }; ~Square() {}; }; class Rhombus : public Parallelogram { public: Rhombus() {}; double area() { return m_height * m_lenght; }; ~Rhombus() {}; }; // 2. Создать класс Car(автомобиль) с полями company(компания) и model(модель).Классы - наследники: PassengerCar(легковой автомобиль) и Bus(автобус). // От этих классов наследует класс Minivan(минивэн).Создать конструкторы для каждого из классов, чтобы они выводили данные о классах. // Создать объекты для каждого из классов и посмотреть, в какой последовательности выполняются конструкторы. Обратить внимание на проблему «алмаз смерти». // Примечание : если использовать виртуальный базовый класс, то объект самого "верхнего" базового класса создает самый "дочерний" класс. class Car { protected: std::string m_company; std::string m_model; public: Car() {}; Car(std::string company, std::string model) : m_company(company), m_model(model) { std::cout << "constructor Car" << std::endl; }; virtual std::string getCompany() { return m_company; } virtual std::string getModel() { return m_model; } virtual ~Car() { std::cout << "destructor Car" << std::endl; }; }; class PassengerCar : virtual public Car { public: PassengerCar() {}; PassengerCar(std::string company, std::string model) : Car(company, model) { std::cout << "constructor PassengerCar" << std::endl; }; std::string getCompany() { return m_company;} std::string getModel() { return m_model; } ~PassengerCar() { std::cout << "destructor PassengerCar" << std::endl; }; }; class Bus : virtual public Car { public: Bus() {}; Bus(std::string company, std::string model) : Car(company, model) { std::cout << "constructor Bus" << std::endl; }; std::string getCompany() { return m_company; } std::string getModel() { return m_model; } ~Bus() { std::cout << "destructor Bus" << std::endl; }; }; class Minivan : public PassengerCar, public Bus { public: Minivan(std::string company, std::string model) : Bus(company, model), PassengerCar(company, model), Car(company, model) { std::cout << "constructor Minivan" << std::endl; }; std::string getCompany() { return m_company; } std::string getModel() { return m_model; } ~Minivan() { std::cout << "destructor Minivan" << std::endl; }; }; // 3. Создать класс : Fraction(дробь).Дробь имеет числитель и знаменатель(например, 3 / 7 или 9 / 2).Предусмотреть, чтобы знаменатель не был равен 0. //Перегрузить : // математические бинарные операторы(+, -, *, / ) для выполнения действий с дробями // унарный оператор(-) // логические операторы сравнения двух дробей(== , != , <, >, <= , >= ). // Примечание : Поскольку операторы < и >= , > и <= — это логические противоположности, попробуйте перегрузить один через другой. // Продемонстрировать использование перегруженных операторов. class Fraction { private: int m_numerator; int m_denominator; public: Fraction() // конструктор по умолчанию { m_numerator = 0; m_denominator = 1; } Fraction(int numerator, int denominator) // конструктор с проверкой на ноль { assert(denominator != 0); m_numerator = numerator; m_denominator = denominator; } int getNumerator() { return m_numerator; } int getDenominator() { return m_denominator; } friend Fraction operator_plus(const Fraction& fract1, const Fraction& fract2); friend Fraction operator_minus(const Fraction& fract1, const Fraction& fract2); friend Fraction operator_multiplication(const Fraction& fract1, const Fraction& fract2); friend Fraction operator_division(const Fraction& fract1, const Fraction& fract2); friend Fraction operator_minus_unar(const Fraction& fract1); friend bool operator_equal(const Fraction& fract1, const Fraction& fract2); friend bool operator_nonEqual(bool operator_equal); friend bool operator_more(const Fraction& fract1, const Fraction& fract2); friend bool operator_less_equal(bool operator_more); friend bool operator_less(const Fraction& fract1, const Fraction& fract2); friend bool operator_more_equal(bool operator_less); }; int gcd(int a, int b) { //наибольший общий делитель while (b > 0) { int c = a % b; a = b; b = c; } return a; } int lcm(int a, int b) { // наименьшее общее кратное return gcd(a, b) * a * b; } Fraction operator_plus(const Fraction& fract1, const Fraction& fract2) { int lcm_tmp = lcm(fract1.m_denominator, fract2.m_denominator); int operator_plus_denominator = fract1.m_denominator * (lcm_tmp / fract1.m_denominator); int operator_plus_numerator = fract1.m_numerator * (lcm_tmp / fract1.m_denominator) + fract2.m_numerator * (lcm_tmp / fract2.m_denominator); return Fraction(operator_plus_numerator, operator_plus_denominator); } Fraction operator_minus(const Fraction& fract1, const Fraction& fract2) { int lcm_tmp = lcm(fract1.m_denominator, fract2.m_denominator); int operator_minus_denominator = fract1.m_denominator * (lcm_tmp / fract1.m_denominator); int operator_minus_numerator = fract1.m_numerator * (lcm_tmp / fract1.m_denominator) - fract2.m_numerator * (lcm_tmp / fract2.m_denominator); return Fraction(operator_minus_numerator, operator_minus_denominator); } Fraction operator_multiplication(const Fraction& fract1, const Fraction& fract2) { int operator_multiplication_denominator = fract1.m_denominator * fract2.m_denominator; int operator_multiplication_numerator = fract1.m_numerator * fract2.m_numerator; return Fraction(operator_multiplication_numerator, operator_multiplication_denominator); } Fraction operator_division(const Fraction& fract1, const Fraction& fract2) { int operator_division_denominator = fract1.m_denominator * fract2.m_numerator; int operator_division_numerator = fract1.m_numerator * fract2.m_denominator; return Fraction(operator_division_numerator, operator_division_denominator); } Fraction operator_minus_unar(const Fraction& fract1) { int operator_division_numerator = -fract1.m_numerator; int operator_division_denominator = fract1.m_denominator; return Fraction(operator_division_numerator, operator_division_denominator); } bool operator_equal(const Fraction& fract1, const Fraction& fract2) { int lcm_tmp = lcm(fract1.m_denominator, fract2.m_denominator); int operator_equal_denominator = fract1.m_denominator * (lcm_tmp / fract1.m_denominator); int operator_numerator1 = fract1.m_numerator * (lcm_tmp / fract1.m_denominator); int operator_numerator2 = fract2.m_numerator * (lcm_tmp / fract2.m_denominator); return operator_numerator1 == operator_numerator2; } bool operator_nonEqual(bool operator_equal) { return !operator_equal; } bool operator_more(const Fraction& fract1, const Fraction& fract2) { int lcm_tmp = lcm(fract1.m_denominator, fract2.m_denominator); int operator_equal_denominator = fract1.m_denominator * (lcm_tmp / fract1.m_denominator); int operator_numerator1 = fract1.m_numerator * (lcm_tmp / fract1.m_denominator); int operator_numerator2 = fract2.m_numerator * (lcm_tmp / fract2.m_denominator); return operator_numerator1 > operator_numerator2; } bool operator_less_equal(bool operator_more) { return !operator_more; } bool operator_less(const Fraction& fract1, const Fraction& fract2) { int lcm_tmp = lcm(fract1.m_denominator, fract2.m_denominator); int operator_equal_denominator = fract1.m_denominator * (lcm_tmp / fract1.m_denominator); int operator_numerator1 = fract1.m_numerator * (lcm_tmp / fract1.m_denominator); int operator_numerator2 = fract2.m_numerator * (lcm_tmp / fract2.m_denominator); return operator_numerator1 < operator_numerator2; } bool operator_more_equal(bool operator_less) { return !operator_less; } // 4. Создать класс Card, описывающий карту в игре БлэкДжек.У этого класса должно быть три поля : масть, значение карты и положение карты // (вверх лицом или рубашкой).Сделать поля масть и значение карты типом перечисления(enum).Положение карты - тип bool. // Также в этом классе должно быть два метода : // метод Flip(), который переворачивает карту, т.е.если она была рубашкой вверх, то он ее поворачивает лицом вверх, и наоборот. // метод GetValue(), который возвращает значение карты, пока можно считать, что туз = 1. class Card { public: enum suit { hearts, spades, cross, diamonds }; // масти enum rank // значение карт { RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8, RANK_9, RANK_10, RANK_jack, RANK_queen, RANK_king, RANK_ace, }; bool faceUp = false; Card() {}; bool Flip(bool faceUp) { faceUp = !faceUp; // проверочный вывод std::cout << "faceUp - " << faceUp << std::endl; return faceUp; } int GetValue(Card::rank cardName) // Есть предупреждение, но собирает и работает. { switch (cardName) { case RANK_2: std::cout << "Value - " << "2" << std::endl; return 2; break; case RANK_3: std::cout << "Value - " << "3" << std::endl; return 3; break; case RANK_4: std::cout << "Value - " << "4" << std::endl; return 4; break; case RANK_5 : std::cout << "Value - " << "5" << std::endl; return 5; break; case RANK_6: std::cout << "Value - " << "6" << std::endl; return 6; break; case RANK_7: std::cout << "Value - " << "7" << std::endl; return 7; break; case RANK_8: std::cout << "Value - " << "8" << std::endl; return 8; break; case RANK_9: std::cout << "Value - " << "9" << std::endl; return 9; break; case RANK_10: std::cout << "Value - " << "10" << std::endl; return 10; break; case RANK_jack: std::cout << "Value - " << "10" << std::endl; return 10; break; case RANK_queen: std::cout << "Value - " << "10" << std::endl; return 10; break; case RANK_king: std::cout << "Value - " << "10" << std::endl; return 10; break; case RANK_ace: std::cout << "Value - " << "1" << std::endl; return 1; break; default: return 0; break; } }; }; int main() { // Task 1. Done. std::cout << "Task 1" << std::endl; Circle Circle; Circle.setRadius(10.0); std::cout << "square of Circle = " << Circle.area() << std::endl; Parallelogram Parallelogram; Parallelogram.setHeight(2); Parallelogram.setLenght(3); std::cout << "square of Parallelogram = " << Parallelogram.area() << std::endl; Rectangle Rectangle; Rectangle.setHeight(4); Rectangle.setLenght(4); std::cout << "square of Rectangle = " << Rectangle.area() << std::endl; Square Square; Square.setHeight(5); Square.setLenght(5); std::cout << "square of Square = " << Square.area() << std::endl; Rhombus Rhombus; Rhombus.setHeight(6); Rhombus.setLenght(6); std::cout << "square of Rhombus = " << Rhombus.area() << std::endl; // Task 2. Done. Прописала и конструкторы, и деструкторы, чтобы было видно, что когда создается и удаляется. Для просмотра остальных заданий это лучше закомментить, // ибо мусорит безбожно. std::cout << "Task 2" << std::endl; Car Car ("BMV", "X5"); std::cout << "Car is " << Car.getModel() << " by "<< Car.getCompany() << " company." << std::endl; PassengerCar PassengerCar("Hundai", "Solaris"); std::cout << "PassengerCar is " << PassengerCar.getModel ()<< " by " << PassengerCar.getCompany() << " company." << std::endl; Bus Bus("Hundai", "Bus"); std::cout << "Car is " << Bus.getModel() << " by " << Bus.getCompany() << " company." << std::endl; Minivan Minivan("Mersedes", "Minivan"); std::cout << "Car is " << Minivan.getModel() << " by " << Minivan.getCompany() << " company." << std::endl; // Task 3. Done. std::cout << "Task 3" << std::endl; Fraction fract1(2, 3); Fraction fract2(1, 7); std::cout << "Arithmetic operators" << std::endl; Fraction NewFractionPlus = operator_plus(fract1, fract2); std::cout << fract1.getNumerator() << "/" << fract1.getDenominator() << " + " << fract2.getNumerator() << "/" << fract2.getDenominator() << " = " << NewFractionPlus.getNumerator() << "/" << NewFractionPlus.getDenominator() << std::endl; Fraction NewFractionMinus = operator_minus(fract1, fract2); std::cout << fract1.getNumerator() << "/" << fract1.getDenominator() << " - " << fract2.getNumerator() << "/" << fract2.getDenominator() << " = " << NewFractionMinus.getNumerator() << "/" << NewFractionMinus.getDenominator() << std::endl; Fraction NewFractionMultiplication = operator_multiplication(fract1, fract2); std::cout << fract1.getNumerator()<<"/"<<fract1.getDenominator()<< " * "<< fract2.getNumerator() << "/" <<fract2.getDenominator()<< " = " << NewFractionMultiplication.getNumerator() << "/" << NewFractionMultiplication.getDenominator() << std::endl; Fraction NewFractionDivision = operator_division(fract1, fract2); std::cout << fract1.getNumerator() << "/" << fract1.getDenominator() << " / " << fract2.getNumerator() << "/" << fract2.getDenominator() << " = " << NewFractionDivision.getNumerator() << "/" << NewFractionDivision.getDenominator() << std::endl; std::cout << "Unary operator" << std::endl; Fraction NewFractionUnar = operator_minus_unar(fract1); std::cout << " - " << fract1.getNumerator() << "/" << fract1.getDenominator() << " = " << NewFractionUnar.getNumerator() << "/" << NewFractionUnar.getDenominator() << std::endl; std::cout << "Logical operators" << std::endl; // логический оператор == std::cout << fract1.getNumerator() << "/" << fract1.getDenominator() << (operator_equal(fract1, fract2) ? " " : " !")<< "= " << fract2.getNumerator() << "/" << fract2.getDenominator()<<std::endl; // логический оператор != через предыдущий std::cout << fract1.getNumerator() << "/" << fract1.getDenominator() << (operator_nonEqual(operator_equal(fract1, fract2)) ? " !" : " ") << "= " << fract2.getNumerator() << "/" << fract2.getDenominator() << std::endl; // Логический оператор > std::cout << fract1.getNumerator() << "/" << fract1.getDenominator() << (operator_more(fract1, fract2) ? " > " : " <= ") << fract2.getNumerator() << "/" << fract2.getDenominator() << std::endl; // Логический оператор <= через предыдущий std::cout << fract1.getNumerator() << "/" << fract1.getDenominator() << (operator_less_equal(operator_more(fract1, fract2)) ? " <= " : " > ") << fract2.getNumerator() << "/" << fract2.getDenominator() << std::endl; // Логический оператор < std::cout << fract1.getNumerator() << "/" << fract1.getDenominator() << (operator_less(fract1, fract2) ? " < " : " >= ") << fract2.getNumerator() << "/" << fract2.getDenominator() << std::endl; // Логический оператор >= через предыдущий std::cout << fract1.getNumerator() << "/" << fract1.getDenominator() << (operator_more_equal(operator_less(fract1, fract2)) ? " >= " : " < ") << fract2.getNumerator() << "/" << fract2.getDenominator() << std::endl; // Task 4. Done. Сделала вывод для проверки - FaceUp и value. Работает, хоть и выводит предупреждение. std::cout << "Task 4" << std::endl; Card card; card.Flip(1); card.GetValue(Card::RANK_king); return 0; }
eec1e5da11a313c2170cab2d70ace0e65e91906a
[ "C++" ]
1
C++
Keylary/Lesson3
81146f848f61a63ee4eca165138e765462b07ab9
bbb855899a5a6050c18c91a7d95af5521405b1c2
refs/heads/master
<file_sep>import os from os.path import join from analyzer import Analyzer def main(): welcomeStr = "Welcome to the Four in a Row Log Analyzer by <NAME> (ffactory)" print("\n {}-".format('- ' * int(len(welcomeStr) / 2 + 1))) print("| {} |".format(welcomeStr)) print("| {message: ^{l}} |".format( message="For more information, please refer to the readme.", l=len(welcomeStr))) print(" {}-\n".format('- ' * int(len(welcomeStr) / 2 + 1))) defaultFile = None currentDir = os.getcwd() for fileStr in os.listdir(currentDir): if fileStr.endswith('.log'): defaultFile = fileStr defaultFileStr = "" if defaultFile != None: defaultFileStr = "[Leave empty for: {}]".format(defaultFile) fileName = None logFile = None fileIsOkay = False while not fileIsOkay: fileName = input( 'Which file would you like to process? {}\n > '.format( defaultFileStr)) if fileName == None or fileName == "": fileName = defaultFile if not os.path.isfile(fileName): print('## That is not a valid file path.') continue with open(fileName, 'r') as f: logFile = f.read() if logFile == None or len(logFile) < 100: print('## That file is empty or too short.') else: fileIsOkay = True continue print('Please try again.') print('\nOK! File loaded successfully.\n') analyzer = Analyzer(logFile) programChoice = None while True: print('Available analyzation choices:') choiceMethods = {} for (index, (choiceStr, choiceMethod)) in enumerate(analyzer.getChoices()): choiceMethods[str(index + 1)] = choiceMethod print(" [{}]: {}".format(index + 1, choiceStr)) programChoice = input('Please make a choice: ') print() choiceMethod = None try: choiceMethod = choiceMethods[programChoice] except KeyError: pass if choiceMethod != None: choiceMethod() print() print( "Would you like to make another analyzation? (Ctrl+C to exit)\n" ) else: print( "## Not a valid choice. Please try again. (Ctrl+C to exit)\n") if __name__ == "__main__": main()<file_sep>from re import match from datetime import datetime class Analyzer: logs: str = None def __init__(self, logs: str) -> None: self.logs = logs if self.logs == None: raise Exception('Logs must not be None!') def getChoices(self) -> list: return [ ("Game Start Time", self.time), ("First Chip Placement", self.first_chip), ("Game Duration", self.game_duration), ] def time(self) -> None: title = '-- Analyzing Game Start Time --' question = 'At what time of day were games requested?' note2 = 'This will take a while...' longestLen = len(question) print(' | {:^{len}} |'.format(title, len=longestLen)) print(' | {:<{len}} |'.format('', len=longestLen)) print(' | {:<{len}} |'.format(question, len=longestLen)) print(' | {:<{len}} |'.format(note2, len=longestLen)) # Ex: (extract time 09:43:11) # Dec 31 09:43:11 (...): rvm>> "MSG::4::REQ_WW" # Jan 01 13:49:00 (...): >> "REQ_WW" gameStartRegex = r'.{7}([:\d]{8}) .*?>> ".*REQ_WW"' times: list = [] for msg in self.logs.splitlines(): matchGameStart = match(gameStartRegex, msg) if matchGameStart != None: times.append(str(matchGameStart.group(1))) timesGrouped: dict = {} for hour in range(0, 24): for minute in range(0, 4): timesGrouped['{:02d}{:02d}'.format(hour, minute * 15)] = 0 for time in times: timeStr = time[0:2] # hour timeMinute = int(time[3:5]) if timeMinute > 45: timeStr += '45' elif timeMinute > 30: timeStr += '30' elif timeMinute > 15: timeStr += '15' else: timeStr += '00' currentTimeGroupCount = timesGrouped[timeStr] timesGrouped[timeStr] = currentTimeGroupCount + 1 totalCount = len(times) biggestCount = max(timesGrouped.values()) print('Total games requested: {}'.format(totalCount)) print() print(' ' + '_' * (1 + 1 * len(timesGrouped))) rowsCount = 16 for row in range(rowsCount, 0, -1): printStr = '' for (time, count) in timesGrouped.items(): printStr += '#' if count / biggestCount >= ( row) / rowsCount else '.' fractionStr = ' ' fraction = (row / rowsCount) * (biggestCount / totalCount) * 100 if row % 4 == 0: fractionStr = '{:>4.1f}'.format(fraction) + '%' print('{}| {} |'.format(fractionStr, printStr)) print(' ' + '-' * (1 + 1 * len(timesGrouped))) printStr = '' for hour in range(0, 24): printStr += '{:02d}h '.format(hour) print(' ' + printStr) # print(' 00 01 02 03 04 05 06 07 08 09') return def first_chip(self) -> None: title = '-- Analyzing First Chip Placement --' question = 'Which of the seven columns was the first chip placed in?' note2 = 'This will take a little while...' longestLen = len(question) print(' | {:^{len}} |'.format(title, len=longestLen)) print(' | {:<{len}} |'.format('', len=longestLen)) print(' | {:<{len}} |'.format(question, len=longestLen)) print(' | {:<{len}} |'.format(note2, len=longestLen)) print() # Ex: (extract player id AAL) # (...) AAL<< "MSG::164::GAME_START:YOU:f63ee5679586" gameStartRegex = r'.*?(.{3})<< "MSG.*GAME_START:YOU.*' # Ex: (extract column 3) # (...) AAL>> "MSG::73::PC:3" placeChipRegex = r'.* {}>> "MSG::.+::PC:(\d)' columns = { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, } searchingForRegex = None for msg in self.logs.splitlines(): if searchingForRegex == None: matchGameStart = match(gameStartRegex, msg) if matchGameStart != None: searchingForRegex = placeChipRegex.format( matchGameStart.group(1)) else: matchPlaceChip = match(searchingForRegex, msg) if matchPlaceChip != None: column = int(matchPlaceChip.group(1)) columns[column] += 1 searchingForRegex = None pass totalCount = sum(columns.values()) print("Total first chip placements: {}".format(totalCount)) print() print(' ' + '_' * (2 + 3 * 7)) rowsCount = 18 for row in range(rowsCount, 0, -1): printStr = '' for column in columns.values(): printStr += '# ' if column / totalCount >= row / rowsCount else '. ' printStr += ' ' print('| {}|'.format(printStr)) print(' -----------------------') print(' 1 2 3 4 5 6 7 ') def game_duration(self): title = '-- Analyzing Game Duration --' question = 'How long did the games last?' note = 'Not showing outliers. (shortest and longest 5%)' note2 = 'This will take a while...' longestLen = len(note) print(' | {:^{len}} |'.format(title, len=longestLen)) print(' | {:<{len}} |'.format('', len=longestLen)) print(' | {:<{len}} |'.format(question, len=longestLen)) print(' | {:<{len}} |'.format(note, len=longestLen)) print(' | {:<{len}} |'.format(note2, len=longestLen)) print() def calculateDuration(start: str, end: str) -> int: '''Calculates duration in seconds between time strings of format "10:48:13"''' startTime = datetime(2000, 1, 1, int(start[0:2]), int(start[3:5]), int(start[6:8])) endTime = datetime(2000, 1, 1, int(end[0:2]), int(end[3:5]), int(end[6:8])) return int((endTime - startTime).total_seconds()) # Ex: (extract player id AAL) # (...) AAL<< "MSG::164::GAME_START:YOU:f63ee5679586" # gameStartRegex = r'.{7}([:\d]{8}) : ([\w]{3})<< "MSG::[\d]+::GAME_START:YOU' # Ex: (extract column 3) # (...) AAL>> "MSG::73::GAME_OVER:YOU:" gameEndRegex = (r'.{7}([:\d]{8}) : ', r'<< "MSG::[\d]+::GAME_OVER') gameDurations = [] splitLines = list( filter( lambda line: line[-15:-1] == 'GAME_START:YOU' or line[-14:-5] == 'GAME_OVER', self.logs.splitlines(keepends=False))) for (index, line) in enumerate(splitLines): if line[25:28] != "MSG": # Speed hack to filter lines that won't match regex anyway continue matchGameStart = match(gameStartRegex, line) if matchGameStart != None: gameStartTimeStr = matchGameStart.group(1) searchingForRegex = gameEndRegex[0] + matchGameStart.group( 2) + gameEndRegex[1] for lineInner in splitLines[index:]: if line[25:28] != "MSG": # Speed hack to filter lines that won't match regex anyway continue matchGameEnd = match(searchingForRegex, lineInner) if matchGameEnd != None: gameEndTimeStr = matchGameEnd.group(1) gameDurations.append( calculateDuration(gameStartTimeStr, gameEndTimeStr)) break gameDurations = sorted(gameDurations) totalCount = len(gameDurations) percentile05index = None percentile95index = None for (index, duration) in enumerate(gameDurations): if index >= totalCount * 0.05 and percentile05index == None: percentile05index = index if index >= totalCount * 0.95 and percentile95index == None: percentile95index = index break durationsGrouped = {} for duration in range(gameDurations[percentile05index], gameDurations[percentile95index], 10): durationsGrouped[duration] = 0 for durationIndex in range(percentile05index, percentile95index): duration = gameDurations[durationIndex] lastDuration = next(iter(durationsGrouped.keys())) for (index, durationGrouped) in enumerate(durationsGrouped): if abs(duration - lastDuration) < abs(duration - durationGrouped): durationsGrouped[lastDuration] += 1 break lastDuration = durationGrouped if index == len(durationsGrouped) - 1: durationsGrouped[lastDuration] += 1 maxCount = max(durationsGrouped.values()) print('Total games played: {}'.format(totalCount)) print() print(' ' + '_' * (3 + 4 * len(durationsGrouped))) rowsCount = 16 for row in range(rowsCount, 0, -1): printStr = '' for (duration, count) in durationsGrouped.items(): printStr += ' # ' if count / maxCount >= ( row) / rowsCount else ' ' fractionStr = ' ' fraction = (row / rowsCount) * (maxCount / totalCount) * 100 if row % 4 == 0: fractionStr = '{:>4.1f}'.format(fraction) + '%' print('{}| {} |'.format(fractionStr, printStr)) print(' ' + '-' * (3 + 4 * len(durationsGrouped))) printStr = '' for duration in durationsGrouped.keys(): printStr += '{:<3d} '.format(duration) print(' ' + printStr) print() print(' Game duration in seconds ->') print() <file_sep># Four in a Row Game Server Log Analyzer ## About ### Authors/Contributors * [<NAME>](https://github.com/ffactory-ofcl) *University Project, January 2021* ### Description - What I did: Analyze real world log data from a game server I host in regard to time of day, game strategy and duration. Includes fancy hand-made graphs. - Background information: This script can analyze files generated by the game server I run. **[The accompanying app](https://github.com/ffactory-ofcl/fourinarow-app)** has around 1700 downloads on the playstore of which 600 still have the app installed. The game is a minimal version of the classic game "Four in a Row" written in **Flutter+Dart**, with added online functionality, friends list, chat, lobby system and local (two players, one device) play. Download it here: [Google Play Store](https://play.google.com/store/apps/details?id=ml.fourinarow) (Android only) ## **A Web-Version [can be found here](https://play.fourinarow.ml/)** It is not bug-free because the mobile version has higher priority. The server is written in Rust. In case you care, [please have a look here](https://github.com/ffactory-ofcl/fourinarow-server) and give it a star :) This "project" contains: * log analyzer with several modi * (real world example) log file ## Run - Open console window in fullscreen. - `python3 src/main.py` - Follow the interactive prompts to explore the logs. ### Custom Configuration Add your own logs in the given format or modify them. ## Documentation The script interactively asks which file you would like to analyze (proposing the first .log file it finds in the script's working directory), lists the available analyzation methods. Then, the selected method is executed, displaying general (how many ...?) stats and a graph with x and y legends. ## Known Issues None. Much larger amounts of data might surface processing time issues but the current set of 500,000 lines only took a couple of seconds to process. ## Useful links [fourinarow-app](https://github.com/ffactory-ofcl/fourinarow-app) [fourinarow-server](https://github.com/ffactory-ofcl/fourinarow-server) # Example output Please use fullscreen to view properly. ``` - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | Welcome to the Four in a Row Log Analyzer by <NAME> (ffactory) | | For more information, please refer to the readme. | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Which file you would like to process? [Leave empty for: fiar-20210105_2131.log] > OK! File loaded successfully. Available analyzation choices: [1]: Game Start Time [2]: First Chip Placement [3]: Game Duration Please make a choice: 3 | -- Analyzing Game Duration -- | | | | How long did the games last? | | Not showing outliers. (shortest and longest 5%) | | This will take a while... | Total games played: 290 _______________________________________________________________________________________________________ 10.3%| # | | # | | # | | # | 7.8%| # # | | # # # # | | # # # # # # | | # # # # # # | 5.2%| # # # # # # # # | | # # # # # # # # # | | # # # # # # # # # # # | | # # # # # # # # # # # | 2.6%| # # # # # # # # # # # | | # # # # # # # # # # # # # # # # # | | # # # # # # # # # # # # # # # # # # # | | # # # # # # # # # # # # # # # # # # # # # # # | ------------------------------------------------------------------------------------------------------- 11 21 31 41 51 61 71 81 91 101 111 121 131 141 151 161 171 181 191 201 211 221 231 241 251 Game duration in seconds -> ```
4e8ac18ab96306067cb21a42a3707981c7cb6f9f
[ "Markdown", "Python" ]
3
Python
ffactory-ofcl/fourinarow-loganalyzer
cdd7a801dec17c3e04fd63186fc35d5ea654bc3f
94dbe587c6a4c3a49322dcb3a9b76fbec6ccce28
refs/heads/master
<repo_name>SporkV/ecomm_demo<file_sep>/db/migrate/20111115235258_create_provinces.rb class CreateProvinces < ActiveRecord::Migration def self.up create_table :provinces do |t| t.string :name t.string :code t.decimal :pst, :precision => 8, :scale => 2 t.decimal :gst, :precision => 8, :scale => 2 t.decimal :hst, :precision => 8, :scale => 2 t.boolean :home_province t.timestamps end end def self.down drop_table :provinces end end <file_sep>/app/controllers/provinces_controller.rb class ProvincesController < ApplicationController def index @provinces = Province.includes(:customers).all @products = Product.all end end <file_sep>/lib/tasks/customer.rake namespace :import do task :customers => :environment do require 'pp' require 'csv' WORKING_DIR = File.dirname(__FILE__) PROVINCES = %w{AB BC MB NB NL NT NS NU ON PE QC SK YT} PROVINCES.each do |p| print "Importing #{p} " count = 0 province = Province.find_by_code(p) CSV.foreach("#{WORKING_DIR}/#{p}_data.csv", { :col_sep => '|'}) do |row| customer = { :name => row[0], :email => row[1], :address => row[2], :city => row[3], :postal_code => row[4], :country => row[6], :province => province } Customer.create(customer) count += 1 end puts count end end task :provinces => :environment do provinces = [ { :name => 'Alberta', :code => 'AB', :pst => 0, :gst => 0.05, :hst => 0, :home_province => false }, { :name => 'British Columbia', :code => 'BC', :pst => 0, :gst => 0, :hst => 0.12, :home_province => false }, { :name => 'Manitoba', :code => 'MB', :pst => 0.07, :gst => 0.05, :hst => 0, :home_province => false }, { :name => 'New Brunswick', :code => 'NB', :pst => 0, :gst => 0, :hst => 0.13, :home_province => false }, { :name => 'Newfoundland and Labrador', :code => 'NL', :pst => 0, :gst => 0, :hst => 0.13, :home_province => false }, { :name => 'North<NAME>erritories', :code => 'NT', :pst => 0, :gst => 0.05, :hst => 0, :home_province => false }, { :name => '<NAME>', :code => 'NS', :pst => 0, :gst => 0, :hst => 0.15, :home_province => false }, { :name => 'Nunavut', :code => 'NU', :pst => 0, :gst => 0.05, :hst => 0, :home_province => false }, { :name => 'Ontario', :code => 'ON', :pst => 0, :gst => 0, :hst => 0.13, :home_province => false }, { :name => '<NAME>', :code => 'PE', :pst => 0.1, :gst => 0.05, :hst => 0, :home_province => false }, { :name => 'Quebec', :code => 'QC', :pst => 0.075, :gst => 0.05, :hst => 0, :home_province => false }, { :name => 'Saskatchewan', :code => 'SK', :pst => 0.05, :gst => 0.05, :hst => 0, :home_province => false }, { :name => 'Yukon', :code => 'YT', :pst => 0, :gst => 0.05, :hst => 0, :home_province => false }, ] provinces.each do |province| Province.create(province) end end end
9182619fec00b4beaedef47b445ca9e5a94153ae
[ "Ruby" ]
3
Ruby
SporkV/ecomm_demo
d16096342f3409f615e9c962a3173c082bf0add0
78cdae09b2c817f361612651ddd24b4337a56a8b
refs/heads/master
<file_sep>class Rules { constructor() { this.rules = [] this.rules['notempty'] = v => !!v || 'Campo requerido'; this.rules['filenotempty'] = v => !!v || 'Campo requerido'; } getRule(name) { return this.rules[name]; } } export default Rules
c423081673cf4e9b5629d5a299cfb663c5903d0a
[ "JavaScript" ]
1
JavaScript
IbanMM/cutreapifront
f019fa98ead209ab1de08028a880e664071e8521
21ec52eddd3812fe8f994b9b422632de7100406e
refs/heads/master
<repo_name>PFight/ts-export-bug<file_sep>/README.md ### Minimal reproducing example of the typescript bug error TS4029: Public property 'baz' of exported class has or is using name 'Baz' from external module "C:/Main/Work/ts-export-bug/A" but cannot be named. ### Steps to reproduce 1. Clone repository 2. Compile sources with typescript version 2.7.0-dev.20171101 tsc 3. See errors $ tsc B.ts(4,5): error TS4029: Public property 'baz' of exported class has or is using name 'Baz' from external module "C:/Main/Work/ts-export-bug/A" but cannot be named. B.ts(6,12): error TS4053: Return type of public method from exported class has or is using name 'Baz' from external module "C:/Main/Work/ts-export-bug/A" but cannot be named. ### Critical details to reproduce 1. Enabled flag `declaration` in compiler options (see `.tsconfig`) 2. Type of field or return type of method are not specified explicit (see workaround) 3. B.ts do not imports A.ts directly, but over Index.ts. So, we have B.ts <- Imports.ts <- A.ts ### Workaround To see workaround add exlicit type to field and specify return type for method. See branch `workaround` for example. <file_sep>/B.ts import * as Index from "./Index"; export class Foo { public baz = new Index.Baz(); public bazbaz() { return Index.Baz; } }
0324057c1560ede8ff49d80e18c52897f4240338
[ "Markdown", "TypeScript" ]
2
Markdown
PFight/ts-export-bug
797f337548652ace77b2a687167a4367e4a9b42e
3059e0167ba1b7e3cf3b605f7dbecb9ab80603e0
refs/heads/master
<repo_name>mastrolinux/ssh-aws<file_sep>/README.md ## Ssh-Aws A simple aws wrapper around the cli## apt-get install python3 python-pip sudo pip install -r requirements.txt It works of mac too, you need python3 libs but it have to run on python2.7 ## Config paramters ## You can copy the config.sample file and change the sercret key and key id values, than put it in a new file. $ cp config.sample config ## How it works ## You can search and login via ssh using the Name tag in AWS console listing $ ./ssh-aws id id ###Scan of Region us-east-1 ### id-04-prod 172.16.17.32 id-02-prod 192.168.127.12 id-03-prod 172.16.17.32 id-01-prod 172.16.58.3 [(u'id-04-prod', u'172.16.17.32'), (u'id-02-prod', u'192.168.127.12'), (u'id-03-prod', u'172.16.17.32'), (u'id-01-prod', u'172.16.58.3')] if there is only one match you can directly login in the server. It tries to use admin as username, feel free to change the code accordingly, will add an option in the future $ ./ssh-aws id-03 id-03 ###Scan of Region us-east-1 ### id-03-prod 172.16.17.32 Connecting to [email protected] Linux id-03-prod 3.2.0-4-amd64 #1 SMP Debian 3.2.54-2 x86_64 Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. Last login: Tue Oct 14 16:41:39 2014 from 172.16.31.10 [admin@id3 ~]$ <file_sep>/ssh-aws #!/usr/bin/env python2.7 import aws_list import argparse parser = argparse.ArgumentParser(description='Find and ssh into AWS servers') parser.add_argument('servername', metavar='servername', type=str, nargs='?', help='name of the server (i.e. store-01)') parser.add_argument('--region', metavar='region', type=str, nargs='?', help='code of the region (i.e. ap-northeast-1), can be "all"') args = parser.parse_args() #print args.get('servername') servername = args.servername or '' region = args.region or 'us-east-1' print servername servers = aws_list.describe(region) aws_list.find_instance_by_name(servers, servername) <file_sep>/aws_list.py #!/usr/bin/env python2.7 from __future__ import print_function from fabric import operations, context_managers import pprint import json import os import sys import subprocess this_dir = os.path.dirname(os.path.realpath(__file__)) os.environ['AWS_CONFIG_FILE'] = os.path.join(this_dir, 'config') os.environ['LC_CTYPE'] = 'en_EN.UTF-8' def _describe(command=None): all_instances = [] with context_managers.hide('running'): instances = json.loads(operations.local(command, capture=True)) to_show = ('InstanceId', 'Tags', 'PublicDnsName', 'PrivateIpAddress') #print instances for instance in instances['Reservations']: if isinstance(instance.get('Instances'), list): current_instance = instance.get('Instances')[0] all_instances = all_instances + [current_instance] # for attribute in to_show: # # pprint(attribute) # yield(current_instance.get(attribute)) return all_instances def describe(region=None): regions = ['us-east-1', 'ap-northeast-1', 'sa-east-1', 'ap-southeast-1', 'ap-southeast-2', 'us-west-2', # 'us-gov-west-1', 'us-west-1', 'eu-west-1'] # 'fips-us-gov-west-1') servers = {} # import pdb; pdb.set_trace() pp = pprint.PrettyPrinter(indent=4) if region: if region != 'all': regions = [region] for current_region in regions: command = 'aws --output json --region %s ec2 describe-instances' % (current_region) print('###Scan of Region %s ###' % current_region) servers[current_region] = _describe(command) return servers def find_instance_by_name(servers, name): pp = pprint.PrettyPrinter(indent=4) names_ips = [] for region, servers_in_region in servers.iteritems(): for server in servers_in_region: for tag in server.get('Tags'): if tag.get('Key') == 'Name': server_name = tag.get('Value') server_ip = server.get('PublicIpAddress') if name in tag.get('Value'): print(server_name, server_ip) if server_ip: names_ips.append((server_name, server_ip)) if len(names_ips) == 1: print("Connecting to admin@%s" % names_ips[0][1]) subprocess.call(['ssh', "admin@%s" % names_ips[0][1]], shell=False) else: print(names_ips[:]) # else: # print("No server found with the string %s in the name" % name) if __name__ == "__main__": if len(sys.argv) > 1: servers = describe(sys.argv[1]) else: servers = describe() find_instance_by_name(servers, 'edit') <file_sep>/requirements.txt Fabric==1.8.0 awscli==1.2.3 bcdoc==0.11.0 botocore==0.23.0 colorama==0.2.5 docutils==0.11 ecdsa==0.10 jmespath==0.1.0 paramiko==1.12.0 ply==3.4 pyasn1==0.1.7 pycrypto==2.6.1 python-dateutil==2.2 rsa==3.1.2 six==1.4.1 wsgiref==0.1.2
886b89eb0a0babad26fa8c6fdec2c26b439b127a
[ "Markdown", "Python", "Text" ]
4
Markdown
mastrolinux/ssh-aws
b2f641ff5decbd44888244d0ddf9986ac3f57e8b
ded1ceabafcd1474c6c216082935226d6e292b80
refs/heads/master
<file_sep>package Main; import Class.Principal; import Class.Pedido; import Class.Equipo; import Class.Panaderia; import java.util.InputMismatchException; import java.util.Scanner; public class App { public static void main(String[] args) throws Exception { Principal principal = null; Scanner sn = new Scanner(System.in); boolean salir = false; int opcion=0; while (!salir) { System.out.println("1. Ingresar cantidad de PEDIDOS"); System.out.println("2. Datos de la PANADERIA"); System.out.println("3. Adicionar PEDIDOS"); System.out.println("4. Listar PEDIDOS con FACTURA"); System.out.println("5. Agregar tipo EQUIPO"); System.out.println("6. Listar EQUIPO"); System.out.println("7. Salir"); System.out.println("Sistema para la Gestion de Panaderia y Equipos"); try { System.out.println("Seleccione una de las opciones"); opcion = sn.nextInt(); switch (opcion) { case 1: System.out.println("Cuantos PEDIDOS desea ingresar"); principal = new Principal(sn.nextInt()); break; case 2: System.out.println("Nombre PANADERIA:"); Panaderia panaderia = new Panaderia(sn.next()); panaderia.setNombrePanaderia(sn.next()); System.out.println("Direccion de PANADERIA:"); panaderia.setDireccionPanaderia(sn.next()); break; case 3: System.out.println("Tipo de PEDIDO:"); Pedido pedido = new Pedido(sn.next()); System.out.println("Con FACTURA? (S/N):"); if (sn.next().equalsIgnoreCase("S")) pedido.setConFactura(true); principal.adicionarPedido(pedido); break; case 4: Pedido[] listado = principal.getListado(); for (int i = 0; i <principal.getCantPedidos() ; i++) { if(listado[i].isConFactura()) System.out.printf("PEDIDO #"+(i+1)+ ": "+listado[i].getTipoPedido()+"\n"); } System.out.println("--------------"); break; case 5: System.out.println("desea agregar EQUIPOS:"); System.out.println("Marque 0:"); Equipo datosEquipo = new Equipo(sn.next()); System.out.println("Tipo de EQUIPO:"); datosEquipo.setTipoEquipo(sn.next()); System.out.println("cantidad de EQUIPOS:"); datosEquipo.setCantidadEquipo(sn.nextInt()); principal.adicionarEquipo(datosEquipo); break; case 6: Equipo[] list= principal.getListadoEquipo().toArray(new Equipo[0]); for (int a = 0; a<10; a++){ System.out.println("El tipo de EQUIPO #"+(a+1)+" es: "+list[a].getTipoEquipo()+", "+" Se necesitan: "+list[a].getCantidadEquipo()+" EQUIPOS"+"\n"); } break; case 7: salir = true; break; default: System.out.println("Solo números entre 1 y 6"); } } catch (InputMismatchException e) { System.out.println("Debes insertar un número"); sn.next(); } } } } <file_sep>package Class; /** * Created by Mario on 14/07/2017. */ public class Equipo { private String tipoEquipo; private int cantidadEquipo; public Equipo (String next) { } public Equipo(String tipoEquipo, int cantidadEquipo) { this.tipoEquipo = tipoEquipo; this.cantidadEquipo = cantidadEquipo; } public String getTipoEquipo() { return tipoEquipo; } public void setTipoEquipo(String tipoEquipo) { this.tipoEquipo = tipoEquipo; } public int getCantidadEquipo() { return cantidadEquipo; } public void setCantidadEquipo(int cantidadEquipo) { this.cantidadEquipo = cantidadEquipo; } }
343e2caa417dc43dd8260a4e19d55928ded6c11e
[ "Java" ]
2
Java
MAgomezpato/Tarea1Consola
8284a43e91b36c299460174e9729e8df3db02913
7ff60cd36c6732ecda994bdf80cb4df328a488b2
refs/heads/master
<repo_name>XquisiteCodes/CDC_cancer_stats<file_sep>/README.md # CDC_cancer_stats Analysis of the cancer dataset from the Centre for Disease, Control and Prevention to determine potential survival of a patient after diagnosis <file_sep>/cancer_stats.py # %% #Importing python modules for data importaion, analysis and visualization import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # %% dataset = pd.read_csv('/home/ezenwa/Documents/Uploaded to Git/CDC_Cancer_stats/BYAGE.TXT', sep = '|', low_memory = False) # %% pd.set_option('display.max_columns', 15) dataset.head() # %% print(dataset.nunique()) print(dataset.info(memory_usage = 'deep')) # %% # Next I want see the percentage of people that died from the cancer and the percentage that were recorded to have cancer but did not pass dataset_event_type = dataset.groupby('EVENT_TYPE').size() dataset_event_type # %% sns.countplot(x = 'EVENT_TYPE', data = dataset) # I am going to be taking 'EVENT_TYPE' feature as my target feature for the putpose of this analysis, so I want to further investigate features that determine the mrtality or a manageable incident # %% dataset.groupby(['EVENT_TYPE','SEX']).size() # Grouping dataset by EVENT_TYPE and SEX, we can see more incidents of females with cancer and also more females passed from cancer. # %% # it seems somes numbers have been imputed as strings, I will convert them to numbers using pandas eval method def eval(a): try: return pd.eval(a) except SyntaxError: return np.nan dataset.COUNT = dataset.COUNT.apply(eval) # %% dataset.CI_LOWER = dataset.CI_LOWER.apply(eval) # %% dataset.CI_UPPER = dataset.CI_UPPER.apply(eval) #%% dataset.RATE = dataset.RATE.apply(eval) dataset.info() #%% dataset[pd.isnull(dataset.RATE)].head(10) #it seems NaN values in RATE occur exactly in the same location accross the other columns containing NaNs #%% #I will be dropping rows that contain NaNs since they occur simmultaneously accross 4 columns dataset.dropna(inplace = True) #%% dataset.info() #Great our data is clean, now we can proceed to analysis and EDA #%% dataset_age = dataset.groupby(['EVENT_TYPE','AGE'])['COUNT'].sum().reset_index() dataset_age #%% plt.figure(figsize = (15,8)) sns.barplot(x = 'AGE', y = 'COUNT', hue = 'EVENT_TYPE', data = dataset) #As expected incidence of cancer is higher from age 50 and mortality is even higher the older you get. #%% dataset_race = dataset.groupby(['RACE', 'EVENT_TYPE']).size().reset_index() dataset_race.columns = ['RACE', 'EVENT_TYPE', 'SIZE'] dataset_race #%% plt.figure(figsize=(15, 8)) sns.barplot(x = 'RACE', y = 'SIZE', hue = 'EVENT_TYPE', data = dataset_race) #race seems to have effect on incidence of cancer #%% dataset_site = dataset.groupby(['SITE','EVENT_TYPE']).size().reset_index() dataset_site.columns = ['SITE', 'EVENT_TYPE', 'SIZE'] dataset_site #%% plt.figure(figsize=(50, 10)) sns.barplot(x = 'SITE', y = 'SIZE', hue = 'EVENT_TYPE', data = dataset_site) #%% #incidence here refers to reported cases of cancer that didn't result in mortality. I want generate a model to predict if a reported case of cancer will most likely result in mortality or not. I will be using logistic regression for this modelling #%% #First will Encode categoriacal data using sklearn's label encoder from sklearn.preprocessing import LabelEncoder #dropping irrelevant columns dataset_modeling = dataset.drop(['POPULATION','RATE','YEAR','COUNT'], axis = 1) cat_data = ['AGE','EVENT_TYPE','RACE','SEX','SITE'] #%% encode = LabelEncoder() dataset_modeling[cat_data] = dataset_modeling[cat_data].apply(encode.fit_transform) dataset_modeling.head() #%% y = dataset_modeling.EVENT_TYPE X = dataset_modeling.drop(['EVENT_TYPE'], axis = 1) print(y.head()) print(X.head()) #%% #Now I will standardize the training dataset from sklearn.preprocessing import StandardScaler #getting columns first cols = X.columns standard = StandardScaler() scaled_X = standard.fit_transform(X) #%% #converting scaled_X back to a dataframe scaled_X = pd.DataFrame(scaled_X, columns=cols) scaled_X.head() #now our data is normalized #%% from sklearn.linear_model import LogisticRegression #for training and fitting the model from sklearn.model_selection import cross_val_score #for cross validation of dataset LR_model =LogisticRegression() #%% scores = cross_val_score(LR_model, scaled_X,y, scoring = 'precision_micro') scores1 = cross_val_score(LR_model, scaled_X,y, scoring = 'recall_micro') scores2 = cross_val_score(LR_model, scaled_X,y, scoring = 'accuracy') scores3 = cross_val_score(LR_model, scaled_X,y, scoring = 'neg_mean_absolute_error') #%% print(scores) print(scores1) print(scores2) print(scores3) #%% from sklearn.model_selection import train_test_split train_X, test_X, train_y, test_y = train_test_split(scaled_X, y, test_size = 0.3) #%% LR_2 = LogisticRegression() model_2 = LR_2.fit(train_X, train_y) #%% from sklearn.metrics import mean_squared_error mean_squared_error(test_y, model_2.predict(test_X)) #%% #%% #%% #%% #%% #%%
1f12667d2f4434b8ba2de594364f8112a7529edb
[ "Markdown", "Python" ]
2
Markdown
XquisiteCodes/CDC_cancer_stats
214f31ac668643d05b79734d7c2586babb0c4fc3
baaeb90fdffa29ca65d43f293cbf57681ae02117
refs/heads/main
<repo_name>jian-dong/s2m2<file_sep>/README.md # Scalable and Safe Multi-agent Motion Planner (S2M2) This is a code repository of Scalable and Safe Multi-agent Motion Planner (S2M2). This repository is associated with the paper [_Scalable and Safe Multi-Agent Motion Planning with Nonlinear Dynamics and Bounded Disturbances_](https://jkchengh.github.io/files/chen2021scalable.pdf). If you have any question, please email me at jkchen 'at' csail.mit.edu, or create an issue [here](https://github.com/jkchengh/s2m2/issues). ## Citation Please cite our work if you would like to use the code. ``` @inproceedings{chen2021scalable, author = {<NAME> and <NAME> and <NAME> and <NAME>}, title = {Scalable and Safe Multi-Agent Motion Planning with Nonlinear Dynamics and Bounded Disturbances}, booktitle = {Proceedings of the Thirty-Fifth AAAI Conference on Artificial Intelligence (AAAI 2021)}, year = {2021} } ``` <file_sep>/util.py import yaml import numpy as np import csv def save_reftrajs(trajs, path): data = dict() for idx in range(len(trajs)): data["Agent %s"%(idx)] = trajs[idx] yaml.Dumper.ignore_aliases = lambda *args: True with open(path, "w") as file: yaml.dump(data, file, indent=4) def write_line(path, line): f = open(path, "a+") f.write(line) f.close() def write_csv(path, list): with open(path, 'a+') as file: writer = csv.writer(file) writer.writerows([list]) def make_rectangle_line(xmin, xmax, ymin, ymax): A_rect = np.array([[-1, 0], [1, 0], [0, -1], [0, 1]]) b = np.array([[-xmin], [xmax], [-ymin], [ymax]]) return (A_rect, b) def make_rectangle_center(x, y, xl, yl): A_rect = np.array([[-1, 0], [1, 0], [0, -1], [0, 1]]) b = np.array([[-(x - xl/2)], [x + xl/2], [-(y - yl/2)], [y + yl/2]]) return (A_rect, b) def make_box_line(xmin, xmax, ymin, ymax, zmin, zmax): if not zmin and not zmax: A_cube = np.array([[-1, 0, 0], [1, 0, 0], [0, -1, 0], [0, 1, 0]]) b = np.array([[-xmin], [xmax], [-ymin], [ymax]]) else: A_cube = np.array([[-1, 0, 0], [1, 0, 0], [0, -1, 0], [0, 1, 0], [0, 0, -1], [0, 0, 1]]) b = np.array([[-xmin], [xmax], [-ymin], [ymax], [-zmin], [zmax]]) return (A_cube, b) def make_box_center(x, y, z, xl, yl, zl): if not z and not zl: A_cube = np.array([[-1, 0, 0], [1, 0, 0], [0, -1, 0], [0, 1, 0]]) b = np.array([[-(x - xl / 2)], [x + xl / 2], [-(y - yl / 2)], [y + yl / 2]]) else: A_cube = np.array([[-1, 0, 0], [1, 0, 0], [0, -1, 0], [0, 1, 0], [0, 0, -1], [0, 0, 1]]) b = np.array([[-(x - xl / 2)], [x + xl / 2], [-(y - yl / 2)], [y + yl / 2], [-(z - zl / 2)], [z + zl / 2]]) return (A_cube, b) <file_sep>/models/car.py from math import * from scipy.integrate import odeint from models.agent import * import random class Car(Agent): def __init__(self, size, velocity, k): self.size = size self.velocity = velocity self.k = k def model(self, q, t, u): x, y, theta = q v, w = u dxdt = v * cos(theta) dydt = v * sin(theta) dthetadt = w return [dxdt, dydt, dthetadt] def controller(self, q, qref, uref): x, y, theta = q xref, yref, thetaref = qref vref, wref = uref k1, k2, k3 = self.k xe = cos(theta) * (xref - x) + sin(theta) * (yref - y) ye = -sin(theta) * (xref - x) + cos(theta) * (yref - y) thetae = thetaref - theta v = vref * cos(thetae) + k1 * xe w = wref + vref * (k2 * ye + k3 * sin(thetae)) return [v, w] def bloating(self, n): return 0 k1, k2, k3 = self.k if n != 0: return sqrt(4 * n / k2) else: return sqrt(4 / k2) def run_model(self, q0, t, qref, uref): q = [q0] u0 = [0, 0] for i in range(0,len(t)): t_step = [t[i-1], t[i]] q1 = odeint(self.model, q0, t_step, args = (u0,)) # + [random.uniform(-0.005, 0.005), # random.uniform(-0.005, 0.005), # random.uniform(-0.005, 0.005),] q0 = q1[1] q.append(q0) u0 = self.controller(q0, qref[i], uref[i]) return q<file_sep>/problems/ground/ground.py from problems.util import * limits = [[0, 60], [0, 60]] Obstacles = [] Thetas = [[20, 48], [30, 48], [40, 48], [20, 12], [30, 12], [40, 12], [12, 20], [12, 30], [12, 40], [48, 20], [48, 30], [48, 40]] A_rect = np.array([[-1, 0], [1, 0], [0, -1], [0, 1]]) Goals = [] lG = [2, 2] for pG in [[20, 12], [30, 12], [40, 12], [20, 48], [30, 48], [40, 48], [48, 20], [48, 30], [48, 40], [12, 20], [12, 30], [12, 40]]: b = np.array([[-(pG[0] - lG[0])], [pG[0] + lG[0]], [-(pG[1] - lG[1])], [pG[1] + lG[1]]]) Goals.append([A_rect, b]) file_name = "ground/problem.yaml" name = "ground" size = 1 velocity = 1 k = [0.5, 0.5, 0.5] agents = [Car(size, velocity, k) for _ in range(12)] write_problem(file_name, name, limits, Obstacles, agents, Thetas, Goals) <file_sep>/problems/util.py import yaml from models.agent import * from models.auv import * from models.car import * from models.hovercraft import * def write_results(file_name, paths, problem_path = None): data = dict() if problem_path is not None: name, limits, Obstacles, agents, Thetas, Goals = read_problem(problem_path) data['name'] = name data["limits"] = limits data["obstacles"] = [write_polytope(obs) for obs in Obstacles] data["agents"] = [write_agent(agent) for agent in agents] data["starts"] = Thetas data["goals"] = [write_polytope(goal) for goal in Goals] data["paths"] = paths yaml.Dumper.ignore_aliases = lambda *args: True with open(file_name, "w") as file: yaml.dump(data, file, indent=4) def read_configuration(file_name): with open(file_name, "r") as file: data = yaml.load(file) min_segs = data["min_segs"] max_segs = data["max_segs"] obstacle_segs = data["obstacle_segs"] return [min_segs, max_segs, obstacle_segs] def read_problem(file_name): with open(file_name, "r") as file: data = yaml.load(file) name = data["name"] limits = data["limits"] Obstacles = [read_polytope(obs) for obs in data["obstacles"]] agents = [read_agent(agent) for agent in data["agents"]] Thetas = data["starts"] Goals = [read_polytope(goal) for goal in data["goals"]] return [name, limits, Obstacles, agents, Thetas, Goals] def write_problem(file_name, name, limits, Obstacles, agents, Thetas, Goals): data = dict() data['name'] = name data["limits"] = limits data["obstacles"] = [write_polytope(obs) for obs in Obstacles] data["agents"] = [write_agent(agent) for agent in agents] data["starts"] = Thetas data["goals"] = [write_polytope(goal) for goal in Goals] yaml.Dumper.ignore_aliases = lambda *args: True with open(file_name, "w") as file: yaml.dump(data, file, indent=4) def write_agent(agent): agent_dict = dict() agent_dict["k"] = agent.k agent_dict["velocity"] = agent.velocity agent_dict["size"] = agent.size if isinstance(agent, Car): agent_dict["type"] = "car" elif isinstance(agent, AUV): agent_dict["type"] = "auv" elif isinstance(agent, Hovercraft): agent_dict["type"] = "hovercraf" return agent_dict def read_agent(agent): type = agent["type"] k = agent["k"] velocity = agent["velocity"] size = agent["size"] if agent["type"] == "car": return Car(size, velocity, k) elif type == "auv": return AUV(size, velocity, k) elif type == "hovercraft": return Hovercraft(size, velocity, k) def write_polytope(poly): A, b = poly lines = [] for idx in range(len(A)): lines.append(A[idx].tolist()+b[idx].tolist()) return lines def read_polytope(poly): A = [] b = [] for idx in range(len(poly)): line = list(poly[idx]) A.append(line[:-1]) b.append([line[-1]]) return [np.array(A), np.array(b)] <file_sep>/algs/xref.py from __future__ import division from math import * import polytope as pc from gurobi import * from numpy import linalg from models.agent import * from timeit import * def add_initial_constraints(problem, vars, Theta): # print("Add Intiail Constraint for Agent") dim = len(Theta) problem.addConstrs(vars[i] == Theta[i] for i in range(dim)) def add_final_constraints(problem, vars, Goal, r): # print("Add Final Constraint for Agent") Af = Goal[0] bf = Goal[1] # Make sure that ending point is at the center of the goal set poly = pc.Polytope(Af, bf) pt = poly.chebXc # Find the center of the goal set problem.addConstrs(vars[i] == pt[i] for i in range(len(pt))) # # Additionally, make sure all the error is contained within the goal set # for row in range(len(Af)): # b = bf[row][0] - linalg.norm(Af[row]) * r # problem.addConstr(LinExpr(Af[row], vars) <= b) def add_obstacle_constraints(problem, p1, p2, O, r): # print("Add Reference Constraints for Agent") if O == []: return None # Add the constraints to avoid the obstacles for (Ao, bo) in O: flags = problem.addVars(len(Ao), vtype=GRB.BINARY) problem.addConstr(flags.sum() <= len(Ao) - 1) for row in range(len(Ao)): b = bo[row] + linalg.norm(Ao[row]) * r problem.addConstr(LinExpr(Ao[row], p1) + 1e5 * flags[row] >= b) problem.addConstr(LinExpr(Ao[row], p2) + 1e5 * flags[row] >= b) def add_moving_obstacle_constraints(problem, p1, p2, t1, t2, MO, r): # print("Add Reference Constraints for Agent") if MO == []: return None # Add the constraints to avoid the obstacles for lb, ub, Ao, bo in MO: # Distance Constraints or Our of Time Window if t2 == None and ub == None: flags = problem.addVars(len(Ao), vtype=GRB.BINARY) problem.addConstr(flags.sum() <= len(Ao)-1) for row in range(len(Ao)): b = bo[row] + linalg.norm(Ao[row]) * r problem.addConstr(LinExpr(Ao[row], p1) + 1e5 * flags[row] >= b) problem.addConstr(LinExpr(Ao[row], p2) + 1e5 * flags[row] >= b) elif t2 == None: flags = problem.addVars(len(Ao) + 1, vtype=GRB.BINARY) problem.addConstr(flags.sum() <= len(Ao)) problem.addConstr(t1 + 1e5 * flags[len(Ao)] >= ub) for row in range(len(Ao)): b = bo[row] + linalg.norm(Ao[row]) * r problem.addConstr(LinExpr(Ao[row], p1) + 1e5 * flags[row] >= b) problem.addConstr(LinExpr(Ao[row], p2) + 1e5 * flags[row] >= b) elif ub == None: flags = problem.addVars(len(Ao) + 1, vtype=GRB.BINARY) problem.addConstr(flags.sum() <= len(Ao)) problem.addConstr(t2 - 1e5 * flags[len(Ao)] <= lb) for row in range(len(Ao)): b = bo[row] + linalg.norm(Ao[row]) * r problem.addConstr(LinExpr(Ao[row], p1) + 1e5 * flags[row] >= b) problem.addConstr(LinExpr(Ao[row], p2) + 1e5 * flags[row] >= b) else: flags = problem.addVars(len(Ao) + 2, vtype=GRB.BINARY) problem.addConstr(flags.sum() <= len(Ao) + 1) problem.addConstr(t1 + 1e5 * flags[len(Ao)] >= ub) problem.addConstr(t2 - 1e5 * flags[len(Ao)+1] <= lb) for row in range(len(Ao)): b = bo[row] + linalg.norm(Ao[row]) * r problem.addConstr(LinExpr(Ao[row], p1) + 1e5 * flags[row] >= b) problem.addConstr(LinExpr(Ao[row], p2) + 1e5 * flags[row] >= b) def add_avoiding_constraints_linear(problem, pA1, pA2, pB1, pB2, r): basis_num = 2 dim = len(pA1) bases = ball_bases(basis_num, dim = dim) # distance variables LAs, LBs lAs = problem.addVars(basis_num, vtype=GRB.CONTINUOUS, lb=0) lBs = problem.addVars(basis_num, vtype=GRB.CONTINUOUS, lb=0) for i in range(basis_num): basis = bases[i] # distance lower bound problem.addConstr(lAs[i] >= LinExpr(basis, pA1) - LinExpr(basis, pA2)) problem.addConstr(lAs[i] >= LinExpr(basis, pA2) - LinExpr(basis, pA1)) problem.addConstr(lBs[i] >= LinExpr(basis, pB1) - LinExpr(basis, pB2)) problem.addConstr(lBs[i] >= LinExpr(basis, pB2) - LinExpr(basis, pB1)) # distance variables LAB lAB2 = problem.addVar(vtype=GRB.CONTINUOUS, lb=0) lAB_flags = problem.addVars(2 * basis_num, vtype=GRB.BINARY) for i in range(basis_num): basis = bases[i] # distance upper bound problem.addConstr(lAB2 - 1e5 * lAB_flags[2 * i] <= LinExpr(basis, pA1) + LinExpr(basis, pA2) - LinExpr(basis, pB1) - LinExpr(basis, pB2)) problem.addConstr(lAB2 - 1e5 * lAB_flags[2 * i + 1] <= - LinExpr(basis, pA1) - LinExpr(basis, pA2) + LinExpr(basis, pB1) + LinExpr(basis, pB2)) # Distance Constraints problem.addConstr(lAB2 >= lAs.sum() + lBs.sum() + 2 * r) def add_constraints(problem, vars, N, dim, Thetas, Goals, O, MO, velocities, sizes, bloat_funcs, min_dur): # Get all the constraints in one function agent_num = len(Thetas) add_time_constraints(problem, vars, agent_num, velocities, N, dim, min_dur) # Add constraints for each agent for idx in range(agent_num): errors = [bloat_funcs[idx](n) + sizes[idx] for n in range(N+1)] p0 = [vars['(A%sN%sD%s)' % (idx, 0, k)] for k in range(dim)] pN = [vars['(A%sN%sD%s)' % (idx, N, k)] for k in range(dim)] add_initial_constraints(problem, p0, Thetas[idx]) add_final_constraints(problem, pN, Goals[idx], errors[N]) for n in range(N): p1 = [vars['(A%sN%sD%s)' % (idx, n, k)] for k in range(dim)] p2 = [vars['(A%sN%sD%s)' % (idx, n+1, k)] for k in range(dim)] t1, t2 = vars['T%s'%(n)], vars['T%s'%(n+1)] add_obstacle_constraints(problem, p1, p2, O, errors[n]) add_moving_obstacle_constraints(problem, p1, p2, t1, t2, MO, errors[n]) pN = [vars['(A%sN%sD%s)' % (idx, N, k)] for k in range(dim)] tN = vars['T%s'%(N)] add_moving_obstacle_constraints(problem, pN, pN, tN, None, MO, sizes[idx]) for i in range(agent_num): for j in range(i): for n in range(N): pA1 = [vars['(A%sN%sD%s)' % (i, n, k)] for k in range(dim)] pA2 = [vars['(A%sN%sD%s)' % (i, n+1, k)] for k in range(dim)] pB1 = [vars['(A%sN%sD%s)' % (j, n, k)] for k in range(dim)] pB2 = [vars['(A%sN%sD%s)' % (j, n+1, k)] for k in range(dim)] rA = bloat_funcs[i](n) rB = bloat_funcs[j](n) r = rA + rB + sizes[i] + sizes[j] add_avoiding_constraints_linear(problem, pA1, pA2, pB1, pB2, r) def get_variables(problem, agent_num, N, dim, limits): vars = {} for i in range(agent_num): for n in range(N + 1): for k in range(dim): lb, ub = limits[k] name = '(A%sN%sD%s)' % (i, n, k) vars[name] = problem.addVar(vtype=GRB.CONTINUOUS, name= name, lb=lb, ub=ub) for n in range(N+1): vars['T%s'%(n)] = problem.addVar(vtype=GRB.CONTINUOUS, name = 'T%s'%(n), lb=0, ub=1e3) return vars def add_time_constraints(problem, vars, agent_num, velocities, N, dim, min_dur): problem.addConstr(vars['T0'] == 0) for idx in range(agent_num): v = velocities[idx] for n in range(N): t1 = v * vars['T%s'%(n)] t2 = v * vars['T%s'%(n + 1)] p1 = [vars['(A%sN%sD%s)' % (idx, n, k)] for k in range(dim)] p2 = [vars['(A%sN%sD%s)' % (idx, n+1, k)] for k in range(dim)] problem.addConstr(t2 - t1 >= min_dur) if dim == 2: for basis in ball_bases(N = 3, dim = dim): problem.addConstr(v * t2 - v * t1 >= LinExpr(basis, p1) - LinExpr(basis, p2)) problem.addConstr(v * t2 - v * t1 >= LinExpr(basis, p2) - LinExpr(basis, p1)) elif dim == 3: problem.addConstr(v * t2 - v * t1 >= p1[0]-p2[0]+p1[1]-p2[1]+p1[2]-p2[2]) problem.addConstr(v * t2 - v * t1 >= p1[0]-p2[0]+p1[1]-p2[1]+p2[2]-p1[2]) problem.addConstr(v * t2 - v * t1 >= p1[0]-p2[0]+p2[1]-p1[1]+p1[2]-p2[2]) problem.addConstr(v * t2 - v * t1 >= p1[0]-p2[0]+p2[1]-p1[1]+p2[2]-p1[2]) problem.addConstr(v * t2 - v * t1 >= p2[0]-p1[0]+p1[1]-p2[1]+p1[2]-p2[2]) problem.addConstr(v * t2 - v * t1 >= p2[0]-p1[0]+p1[1]-p2[1]+p2[2]-p1[2]) problem.addConstr(v * t2 - v * t1 >= p2[0]-p1[0]+p2[1]-p1[1]+p1[2]-p2[2]) problem.addConstr(v * t2 - v * t1 >= p2[0]-p1[0]+p2[1]-p1[1]+p2[2]-p1[2]) def set_objective(problem, vars, N): problem.setObjective(vars['T%s'%(N)], GRB.MINIMIZE) def get_gb_xref(models, Thetas, Goals, limits, O, MO, N_min, N, min_dur = 0): # print("Start Searching for Reference Trajectories") agent_num = len(models) velocities = [model.velocity for model in models] sizes = [model.size for model in models] bloat_funcs = [model.bloating for model in models] dim = len(Goals[0][0][0]) for n in range(N_min, N): # print("--------") # print("Horizon", n) problem = Model("xref") problem.setParam(GRB.Param.OutputFlag, 0) problem.setParam(GRB.Param.IntFeasTol, 1e-9) problem.setParam(GRB.Param.MIPGap, 0.5) # problem.setParam(GRB.Param.NonConvex, 2) # Temporary vars = get_variables(problem, agent_num, n, dim, limits) add_constraints(problem, vars, n, dim, Thetas, Goals, O, MO, velocities, sizes, bloat_funcs, min_dur) set_objective(problem, vars, n) # problem.write("test.lp") start = default_timer() problem.optimize() end = default_timer() if problem.status == GRB.OPTIMAL: # for v in problem.getVars(): print(v.varName, v.x) ma_nodes = [] front_time = -1 for idx in range(agent_num): nodes = [] for i in range(n + 1): time = vars['T%s'%(i)].x x_new = [time] for k in range(dim): x_new = x_new + [vars['(A%sN%sD%s)' % (idx, i, k)].x] if x_new[0] > front_time: front_time = x_new[0] nodes = nodes + [x_new] ma_nodes = ma_nodes + [nodes] problem.dispose() print_solution(ma_nodes, end-start) return ma_nodes else: # print('No solution') problem.dispose() def ball_bases(N=3, dim=2): if dim == 2: p = pi / N bases = [[cos(n * p), sin(n * p)] for n in range(N)] # print(bases) return bases elif dim == 3: return [[1, 0, 0], [0, 1, 0], [0, 0, 1]] def print_solution(ma_nodes, time): agent_num = len(ma_nodes) for idx in range(agent_num): print("Printing Solution with Solving Time ", time, "s") # print("Agent %s Solution"%(idx)) nodes = ma_nodes[idx] seg_num = len(nodes) for i in range(seg_num): print("[%s] %s"%(i, nodes[i]))<file_sep>/algs/centralized.py from algs.xref import * # Main controller algorithm def centralized_algo(velocities, sizes, bloating_functions, Thetas, goals, limits, obstacles, min_segs, max_segs): agent_num = len(sizes) collisions = [[]] * agent_num # Get the reference nodes print("Search Begins") ma_nodes = get_gb_xref(Thetas, goals, obstacles, limits, velocities, sizes, bloating_functions, collisions, min_segs, max_segs) if ma_nodes != None: print("Solution Found!") return ma_nodes print("Fail!") return None <file_sep>/models/hovercraft.py # 3d Kinematic Model # Written by: <NAME> from math import * from scipy.integrate import odeint from models.agent import * class Hovercraft(Agent): def __init__(self, size, velocity, k): self.size = size self.velocity = velocity self.k = k def model(self, q, t, u): x, y, z, theta = q v, vz, w = u dxdt = v*cos(theta) dydt = v*sin(theta) dzdt = vz dthetadt = w return [dxdt, dydt, dzdt, dthetadt] def controller(self, q, qref, uref): k1, k2, k3, kp = self.k xref, yref, zref, rollref, pitchref, yawref = qref x, y, z, theta = q vxyref = uref[0]*cos(pitchref) vzref = uref[0]*sin(pitchref) _, _, uyaw_ref = uref[1] xe = cos(theta) * (xref - x) + sin(theta) * (yref - y) ye = -sin(theta) * (xref - x) + cos(theta) * (yref - y) ze = zref - z thetae = pitchref - theta vxy = vxyref * cos(thetae) + k1 * xe w = uyaw_ref + vxyref * (k2 * ye + k3 * sin(thetae)) vz = vzref + kp * ze return [vxy, vz, w] def bloating(self, n): return 0.15 k1, k2, k3, kp = self.k if n != 0: return sqrt(4*n/k2) else: return 0 def run_model(self, q0, t, qref, uref): q = [q0] u0 = [0, 0, 0] for i in range(0,len(t)): t_step = [t[i-1], t[i]] q1 = odeint(self.model, q0, t_step, args = (u0,)) q0 = q1[1] # print(q0) q.append(q0) u0 = self.controller(q0, qref[i], uref[i]) return q <file_sep>/viz/animate.py import matplotlib.animation as animation from viz.util import * import os from models.agent import * def animate_results(models, limits, obstacles, Thetas, goals, ma_segs, name): agent_num = len(models) dim = len(limits) fig, axes = plot_env(limits, obstacles) plot_goals(goals) interval = 20 total_frames = 500 total_time = max([ma_segs[idx][-1][0][-1] for idx in range(agent_num)]) if dim == 2: paths = extract_paths(models, Thetas, ma_segs) ref_patches = [] tru_patches = [] err_patches = [] for idx in range(agent_num): ref_x, ref_y, _, tru_x, tru_y, _, times = paths[idx] ref_patch = plt.Circle((ref_x[0], ref_y[0]), 0, fc='k') tru_patch = plt.Circle((tru_x[0], tru_y[0]), models[idx].size, fc='navy', alpha = 0.7) err_patch = plt.Circle((ref_x[0], ref_y[0]), models[idx].size, fc='lightsteelblue', alpha = 0.4) ref_patches.append(ref_patch) tru_patches.append(tru_patch) err_patches.append(err_patch) # init def init(): for idx in range(agent_num): ref_x, ref_y, _, tru_x, tru_y, _, times = paths[idx] ref_patches[idx].center = (ref_x[0], ref_y[0]) tru_patches[idx].center = (tru_x[0], tru_y[0]) err_patches[idx].center = (ref_x[0], ref_y[0]) for patch in ref_patches + tru_patches + err_patches: axes.add_patch(patch) return ref_patches + tru_patches + err_patches # animate tpf = total_time / total_frames def animate(f): ref, tru = [], [] for idx in range(agent_num): ref_x, ref_y, _, tru_x, tru_y, _, times = paths[idx] step = 0 while (step < len(times) - 1) and (times[step] < tpf * f): step = step + 1 ref_patches[idx].center = (ref_x[step], ref_y[step]) tru_patches[idx].center = (tru_x[step], tru_y[step]) err_patches[idx].center = (ref_x[step], ref_y[step]) if step == len(ref_x) - 1: error = models[idx].size else: error = (models[idx].size + models[idx].bloating(step)) err_patches[idx].width = 2 * error err_patches[idx].height = 2 * error return ref_patches + tru_patches + err_patches ani = animation.FuncAnimation(fig, animate, frames = total_frames, init_func=init, blit=True, interval = interval) # fig.subplots_adjust(left=0.01, bottom=0.01, right=0.99, top=0.99, wspace=None, hspace=None) path = os.path.abspath("results/plots/%s.mp4" % (name)) ani.save(path, writer='ffmpeg') <file_sep>/problems/parking/parking.py from problems.util import * A_rect = np.array([[-1,0], [1,0], [0,-1], [0,1]]) b01 = np.array([[-25], [80], [-45], [50]]) b02 = np.array([[-8], [58], [-8], [19]]) b1 = np.array([[-40], [41], [-30], [40]]) b2 = np.array([[-1], [41], [-29], [30]]) b3 = np.array([[-1], [2], [-1], [29]]) b4 = np.array([[-2], [59], [-1], [2]]) b5 = np.array([[-58], [59], [-2], [40]]) b6 = np.array([[-58], [89], [-40], [41]]) b7 = np.array([[-88], [89], [-41], [58]]) b8 = np.array([[-15], [89], [-58], [59]]) b9 = np.array([[-15], [16], [-40], [58]]) b10 = np.array([[-15], [40], [-39], [40]]) Obstacles = [(A_rect, b01), (A_rect, b02), (A_rect, b1), (A_rect, b2), (A_rect, b3), (A_rect, b4), (A_rect, b5), (A_rect, b6), (A_rect, b7), (A_rect, b8), (A_rect, b9), (A_rect, b10)] Thetas = [[35, 55], [50, 55], [65, 55]] Goals = [] A_rect = np.array([[-1,0], [1,0], [0,-1], [0,1]]) pG1 = [45, 5] lG1 = [10, 10] b3 = np.array([[-(pG1[0] - lG1[0])], [pG1[0] + lG1[0]], [-(pG1[1] - lG1[1])], [pG1[1] + lG1[1]]]) Goals.append((A_rect, b3)) pG2 = [30, 5] lG2 = [10, 10] b4 = np.array([[-(pG2[0] - lG2[0])], [pG2[0] + lG2[0]], [-(pG2[1] - lG2[1])], [pG2[1] + lG2[1]]]) Goals.append((A_rect, b4)) pG3 = [15, 5] lG3 = [10, 10] b5 = np.array([[-(pG3[0] - lG3[0])], [pG3[0] + lG3[0]], [-(pG3[1] - lG3[1])], [pG3[1] + lG3[1]]]) Goals.append((A_rect, b5)) limits = [[0, 90], [0, 60]] file_name = "problem.yaml" name = "parking" size = 2.5 velocity = 1 k = [0.5, 0.5, 0.5] agents = [Car(size, velocity, k) for _ in range(3)] write_problem(file_name, name, limits, Obstacles, agents, Thetas, Goals)<file_sep>/MAMP.py # Run benchmarks import argparse import sys from algs.centralized import centralized_algo from algs.decentralized import decentralized_algo parser = argparse.ArgumentParser() parser.add_argument("models", nargs='+') parser.add_argument("--env") parser.add_argument("--min_segs") parser.add_argument("--max_segs") parser.add_argument("--method") parser.add_argument("--viz") args = parser.parse_args() # check method (Default = Centralized) if args.method == None: method = "decentralized" else: method = args.method # check the number of line segments if args.max_segs == None: max_segs = 100 else: max_segs = int(args.max_segs) if args.min_segs == None: min_segs = 3 else: min_segs = int(args.min_segs) # Plot the problem and the test runs if __name__ == '__main__': if method == "centralized": trajs = centralized_algo(args.models, args.env, min_segs, max_segs) elif method == "decentralized": trajs = decentralized_algo(args.models, args.env, min_segs, max_segs) if bool(args.plot) == True: True else: sys.exit()<file_sep>/algs/collision.py import numpy as np from numpy import linalg, float16, float64 from math import * import pypoman as ppm from models.agent import * def traj2obs(ref, model, e = 0.001, steps = 10): O = [] time_step = (ref[-1][0] - ref[0][0]) / steps rref = ref.copy() # print("Start", ref[0][0], "End", ref[-1][0]) for j in range(1,steps): t = j * time_step + rref[0][0] # print(j, t) index = next((i for i in range(len(rref) - 1) if rref[i][0] <= t and t <= rref[i + 1][0]), None) assert index != None t1, t2 = rref[index][0], rref[index+1][0] p1, p2 = np.array(rref[index][1:]), np.array(rref[index+1][1:]) k = (p2 - p1) / (t2 - t1) p = p1 + k * (t - t1) rref.insert(index+1, [t] + [x for x in p]) # Each Segment To Obstacle for i in range(len(rref)-1): # print("Traj Seg[%s/%s] to Moving Obstacles"%(i, len(rref)-1)) t1, t2 = rref[i][0], rref[i+1][0] p1, p2 = np.array(rref[i][1:]), np.array(rref[i+1][1:]) R = model.size + model.bloating(i) + e # print(R) # Static during This Segment if t2 == t1: k = np.array([0] * len(p1)) # Moving during This Segment else: k = (p2 - p1) / (t2 - t1) obs = seg2obs(t1, t2, k, R, p1) O.append(obs) # Final Position as A Staic Obstacle # print("Traj Seg[%s/%s] to Moving Obstacles" % (len(rref)-1, len(rref)-1)) obs = seg2obs(rref[-1][0], None, np.array([0] * len(p1)), model.size + e, np.array(rref[-1][1:])) O.append(obs) return O def seg2obs(lb, ub, k, R, p): for idx in range(len(k)): if -0.01 < k[idx] < 0.01: k[idx] = 0 norm = linalg.norm(k) if len(k) == 2: if linalg.norm(k) != 0: k = k / linalg.norm(k) vk = np.array([-k[1], k[0]]) # print(linalg.norm(k)) # print("Direction", k, "Vertical Direction", vk) vertices = [p + R * (- k + vk), p + R * (- k - vk), p + k * norm * (ub - lb) + R * (k + vk), p + k * norm * (ub - lb) + R * (k - vk)] else: vertices = [p + np.array([R, R]), p + np.array([R, -R]), p + np.array([-R, R]), p + np.array([-R, -R])] # TODO CDD LIB cannot Handle Float64 elif len(k) == 3: if linalg.norm(k) != 0: k = k / linalg.norm(k) k1, k2 = [0] * 3, [0] * 3 for ia, ib, ic in [[0, 1, 2], [0, 2, 1], [2, 0, 1]]: k1[ia], k1[ib], k1[ic] = [-k[ic], -k[ic], k[ia] + k[ib]] if linalg.norm(np.array(k1)) > 1e-3: break assert(linalg.norm(np.array(k1)) > 1e-3) k2[ia], k2[ib], k2[ic] = [-k[ia]*k[ib] - k[ib]*k[ib] - k[ic]*k[ic], k[ia]*k[ia] + k[ia]*k[ib] + k[ic]*k[ic], k[ia]*k[ic] - k[ib]*k[ic]] k1 = np.array(k1) k2 = np.array(k2) k1 = float64(k1 / linalg.norm(k1)) k2 = float64(k2 / linalg.norm(k2)) vertices = [p + R * (- k + k1 + k2), p + R * (- k + k1 - k2), p + R * (- k - k1 + k2), p + R * (- k - k1 - k2), p + k * norm * (ub - lb) + R * (- k + k1 + k2), p + k * norm * (ub - lb) + R * (- k + k1 - k2), p + k * norm * (ub - lb) + R * (- k - k1 + k2), p + k * norm * (ub - lb) + R * (- k - k1 - k2)] else: vertices = [p + np.array([R, R, R]), p + np.array([R, R, -R]), p + np.array([R, -R, R]), p + np.array([R, -R, -R]), p + np.array([-R, R, R]), p + np.array([-R, R, -R]), p + np.array([-R, -R, R]), p + np.array([-R, -R, -R])] # TODO CDD LIB cannot Handle Float64 vertices = [float64(v) for v in vertices] #print(lb, ub, k, R, p) #print(vertices) # print("\n") A, b = ppm.compute_polytope_halfspaces(vertices) return lb, ub, A, b def find_collision(refA, modelA, refB, modelB, request = 'first'): rA = modelA.size rB = modelB.size bloatingA = modelA.bloating bloatingB = modelB.bloating refA = refA + [np.array([1e4] + list(refA[-1][1:]))] refB = refB + [np.array([1e4] + list(refB[-1][1:]))] areaA, areaB = [], [] timesA = [refA[i][0] for i in range(len(refA))] timesB = [refB[i][0] for i in range(len(refB))] times = sorted(list(set().union(timesA, timesB))) # print("A, Times", timesA) # print("B, Times", timesB) # print("Times", times) for i in range(len(times)-1): start_time, end_time = times[i], times[i+1] # print("\n-- [%s, %s]"%(start_time, end_time)) indexA = next((i for i in range(len(timesA)-1) if timesA[i] <= start_time and end_time <= timesA[i+1]), None) assert indexA != None tA1, tA2 = timesA[indexA], timesA[indexA+1] pA1, pA2 = np.array(refA[indexA][1:]), np.array(refA[indexA+1][1:]) RA = rA if indexA + 1 != len(refA) - 1: RA = RA + + bloatingA(indexA) kA = (pA2 - pA1) / (tA2 - tA1) bA = pA1 + kA * (start_time - tA1) # positions at start_time of this segment indexB = next((i for i in range(len(timesB) - 1) if timesB[i] <= start_time and timesB[i+1] >= end_time), None) assert indexB != None tB1, tB2 = timesB[indexB], timesB[indexB+1] pB1, pB2 = np.array(refB[indexB][1:]), np.array(refB[indexB+1][1:]) RB = rB if indexB + 1 != len(refB) - 1: RB = RB + + bloatingB(indexB) kB = (pB2 - pB1) / (tB2 - tB1) bB = pB1 + kB * (start_time - tB1) kAB = kA - kB bAB = bA - bB R = RA + RB if len(kAB) == 2: a = kAB[0] ** 2 + kAB[1] ** 2 b = 2 * kAB[0] * bAB[0] + 2 * kAB[1] * bAB[1] c = bAB[0] ** 2 + bAB[1] ** 2 - R ** 2 elif len(kAB) == 3: a = kAB[0] ** 2 + kAB[1] ** 2 + kAB[2] ** 2 b = 2 * kAB[0] * bAB[0] + 2 * kAB[1] * bAB[1] + 2 * kAB[2] * bAB[2] c = bAB[0] ** 2 + bAB[1] ** 2 + bAB[2] ** 2 - R ** 2 # print("IndexA: %s, IndexB: %s"%(indexA, indexB)) # print("A: [%s -> %s]"% (refA[indexA], refA[indexA+1])) # print("B: [%s -> %s]"% (refB[indexB], refB[indexB+1])) # print("R:", R, "RA:", RA, "RB", RB) # print("kAB:", kAB, "kA:", kA, "kB:", kB) # print("bAB:", bAB, "bA:", bA, "bB:", bB) # print("a = %s, b = %s, c = %s"%(a, b, c)) if a == 0: # print("Constant Relative Distance") assert b == 0 if c <= 0: lb, ub = start_time, end_time areaA.append([lb, ub, kA, RA, bA]) areaB.append([lb, ub, kB, RB, bB]) # print("Collision Found") # print("A", areaA) # print("B", areaB) if request == 'first': return [areaA[0], areaB[0]] elif b ** 2 - 4 * a * c >= 0: d = sqrt(b ** 2 - 4 * a * c) roots = sorted([(-b - d) / (2 * a), (-b + d) / (2 * a)]) lb, ub = np.array(roots) + np.array([start_time, start_time]) # add time offset # print("Meet during [%s, %s]"%(lb, ub)) if start_time <= ub and lb <= end_time: lb = max(start_time, lb) ubA = min(end_time, ub) ubB = min(end_time, ub) areaA.append([lb, ubA, kA, RA, bA + kA * (lb - start_time)]) areaB.append([lb, ubB, kB, RB, bB + kB * (lb - start_time)]) # print("Collision Found") # print("A", areaA) # print("B", areaB) if request == 'first': return [areaA[0], areaB[0]] if request == 'first': return [None, None] elif request == 'all': return [areaA, areaB]<file_sep>/viz/plot.py from viz.util import * from algs.collision import * import os def plot_results(models, limits, Obstacles, Thetas, Goals, ma_segs, name, MO = [], refs = None): plt.close('all') agent_num = len(models) fig, axes = plot_env(limits, Obstacles) # plot_goals(Goals) # plot_thetas(Thetas) # for mo in MO: # for obs in mo: # A = obs[2] # b = np.array([[e] for e in obs[3]]) # plot_polytope_3d(A, b, axes) paths = extract_paths(models, Thetas, ma_segs) for idx in range(agent_num): if len(Thetas[idx]) == 2: ref_x, ref_y, _, tru_x, tru_y, _, _ = paths[idx] ref_x, ref_y, _, tru_x, tru_y, _, _ = paths[idx] # axes.plot(ref_x, ref_y, color='k', linewidth = 2, linestyle = 'dashed') # axes.plot(tru_x, tru_y, color='purple', linewidth = 3, linestyle='dashed',) if refs is not None: x = [p[1] for p in refs[idx]] y = [p[2] for p in refs[idx]] axes.plot(x, y,color='k', linestyle = 'dashed', linewidth = 2, marker = 'o') elif len(Thetas[idx]) == 3: ref_x, ref_y, ref_z, tru_x, tru_y, tru_z, _, _, _, _ = paths[idx] axes.plot(ref_x, ref_y, ref_z, color='k') axes.plot(tru_x, tru_y, tru_z, 'r--') fig.show() path = os.path.abspath("results/%s.svg" % (name)) fig.savefig(path, bbox_inches='tight', pad_inches = 0) return None <file_sep>/problems/mit/mit.py from util import * from problems.util import * Obstacles = [make_box_line(-12, -8, 2, 2, 0, 5.8), make_box_line(8, 12, 2, 2, 0, 5.8)] Thetas = [[-6, -2, 3], [-4, -2, 3], [-2, -2, 3], [0, -2, 3], [2, -2, 3], [4, -2, 3], [6, -2, 3], [-2, -4, 3], [-2, -6, 3], [-2, -8, 3], [-4, -8, 3], [-6, -8, 3], [2, -4, 3], [2, -6, 3], [2, -8, 3], [4, -8, 3], [6, -8, 3], ] Goals = [make_box_center(-14, 8, 1, 2, 2, 2), make_box_center(-12, 8, 3, 2, 2, 2), make_box_center(-10, 8, 5, 2, 2, 2), make_box_center(-8, 8, 3, 2, 2, 2), make_box_center(-6, 8, 1, 2, 2, 2), make_box_center(-4, 8, 3, 2, 2, 2), make_box_center(-2, 8, 5, 2, 2, 2), make_box_center(0, 8, 3, 2, 2, 2), make_box_center(2, 8, 1, 2, 2, 2), make_box_center(6, 8, 1, 2, 2, 2), make_box_center(6, 8, 3, 2, 2, 2), make_box_center(6, 8, 5, 2, 2, 2), make_box_center(10, 8, 5, 2, 2, 2), make_box_center(12, 8, 5, 2, 2, 2), make_box_center(12, 8, 3, 2, 2, 2), make_box_center(12, 8, 1, 2, 2, 2), make_box_center(14, 8, 5, 2, 2, 2),] limits = [[-16, 16], [-10, 10], [0.5, 6]] size = 0.5 velocity = 1 k = [2, 2, 2] file_name = "problem.yaml" name = "mit" agents = [AUV(size, velocity, k) for _ in range(17)] write_problem(file_name, name, limits, Obstacles, agents, Thetas, Goals) <file_sep>/algs/decentralized.py from algs.xref import * from algs.collision import * from queue import * from networkx import * from copy import deepcopy from timeit import * # Main controller algorithm def decentralized_algo(models, thetas, goals, limits, obstacles, min_segs, max_segs, obs_steps, min_dur, timeout = 300): agent_num = len(models) params = [models, thetas, goals, limits, obstacles, min_segs, max_segs, obs_steps, min_dur] print("\n----- 0 -----") root = Node(agent_num) for idx in range(agent_num): plan = root.update_plan(idx, params) if plan == None: return None q = PriorityQueue() q.put(root) times = 0 start_time = default_timer() while not q.empty(): if default_timer() - start_time > timeout: print("Timeout!") return None times = times + 1 node = q.get() print("\n-----", times, "-----") print("Orders:", node.G.edges) print("Makespan =", node.makespan) # Check Collision colliding_agents = node.earliest_colliding_agents(params) print("Colliding Agents:", colliding_agents) # Solution Found if colliding_agents == None: print("[*] Solution Found!") return node.plans # Resolve Collision for (j, i) in [colliding_agents, (colliding_agents[1], colliding_agents[0])]: # Update Node print("\n[*] Split on (%s < %s)"%(j, i)) new_node = node.copy() new_node = new_node.update_node((j, i), params) if new_node == None: print("Infeasiblae") else: print("Feasible and Push") q.put(new_node) return None class Node: def __init__(self, num, plans = [], makespan = 0, G = nx.DiGraph(), orders = set(), collisions = {}): # params [num] self.num = num # plans [plans, makespan] if plans == []: plans = [None for i in range(num)] self.plans = plans self.makespan = makespan # orders [G] G.add_nodes_from(list(range(num))) if orders != set(): G.add_edges_from(orders) self.G = G # collisions self.collisions = collisions # only specified for agents with certain orderigns def __lt__(self, other): # if (self.makespan < other.makespan): return True # elif (self.makespan > other.makespan): return False # else: return len(self.G) < len(other.G) if len(self.G.edges) > len(other.G.edges): return True elif len(self.G.edges) < len(other.G.edges): return False else: return self.makespan < other.makespan def copy(self, memodict={}): return Node(self.num, plans = deepcopy(self.plans), makespan = self.makespan, G = self.G.copy(), collisions = deepcopy(self.collisions)) def agents(self): return set(list(range(self.num))) def higher_agents(self, idx): return ancestors(self.G, idx) def lower_agents(self, idx): return descendants(self.G, idx) def sorted_agents(self, nodes): H = self.G.subgraph(nodes) return list(topological_sort(H)) def add_order(self, order): higher_agents = self.higher_agents(order[1]) lower_agents = self.lower_agents(order[1]) if order[0] in higher_agents: status = "existing" elif order[0] in lower_agents: status = "inconsistent" else: self.G.add_edge(*order) status = "added" return status def earliest_colliding_agents(self, params): models, _, _, _, _, _, _, _, _ = params earliest_time = 1e6 colliding_agents = None for i in range(self.num): for j in self.agents() - set([i]): time = 1e8 # print(" -- Check Collison for (%s, %s)" % (i, j)) if ("%s-%s" % (i, j) in self.collisions and self.collisions["%s-%s" % (i, j)] == "free"): 1 # print(" -- [Collision Free] Previously Checked.") elif ("%s-%s" % (i, j) in self.collisions and self.collisions["%s-%s" % (i, j)] != "free"): # print(" -- [Collision Found] Previously Checked.") time = self.collisions["%s-%s" % (i, j)] else: area, _ = find_collision(self.plans[i], models[i], self.plans[j], models[j]) if area != None: # print(" -- [Collision Found].") self.collisions["%s-%s" % (i, j)] = area[0] self.collisions["%s-%s" % (j, i)] = area[0] time = area[0] else: # print(" -- [Collision Free].") self.collisions["%s-%s" % (i, j)] = "free" self.collisions["%s-%s" % (j, i)] = "free" if time < earliest_time: earliest_time = time colliding_agents = (i, j) print(" -- [\] Update Colliding Agents.", i, "-", j) return colliding_agents def update_node(self, order, params): # Check Ordering Status status = self.add_order(order) print("Adding Order Status: ", status) # assert status == "added" if status == "inconsistent": return None # Plan for All the Affected Agents idx = order[1] models, _, _, _, _, _, _, _, _ = params agents = [idx] # Only Update Affected Agents # agents = [idx] + self.sorted_agents(self.lower_agents(idx)) print("Agents to Update:", agents) for k in agents: print("- Update Plan for Agent", k) higher_agents = self.higher_agents(k) # check colliding replan = False for j in higher_agents: # print(" -- Check Collison for (%s, %s)" % (k, j)) if ("%s-%s" % (k, j) in self.collisions and self.collisions["%s-%s" % (k, j)] == "free"): 1 # print(" -- [Collision Free] Previously Checked.") elif ("%s-%s" % (k, j) in self.collisions and self.collisions["%s-%s" % (k, j)] != "free"): # print(" -- [Collision Found] Previously Checked.") replan = True break else: if self.plans[j] != None: self.collisions["%s-%s" % (k, j)] != area[0] self.collisions["%s-%s" % (j, k)] != area[0] area, _ = find_collision(self.plans[k], models[k], self.plans[j], models[j]) if area != None: self.collisions["%s-%s" % (k, j)] != "free" self.collisions["%s-%s" % (j, k)] != "free" # print(" -- [Collision Found].") replan = True break # else: print(" -- [Collision Free].") # Update If colliding if k == idx or replan: plan = self.update_plan(k, params) if plan == None: print("- Update Fails for Agent", k) return None print("- Update Succeed for Agent", k) else: print("- No need to update for Agent", k) return self def update_plan(self, k, params): models, thetas, goals, limits, obstacles, min_segs, max_segs, obs_steps, min_dur = params print("- Find Collision and Reroute") MO = [] for j in self.higher_agents(k): MO = MO + traj2obs(self.plans[j], models[j], steps = obs_steps) # if self.plans[k] == None: # Nmin, Nmax = min_segs, max_segs # else: # Nmin = len(self.plans[k]) + 1 # Nmax = Nmin + 2 Nmin, Nmax = min_segs, max_segs new_plan = get_gb_xref([models[k]], [thetas[k]], [goals[k]], limits, obstacles, MO, Nmin, Nmax, min_dur = min_dur) if new_plan == None: print("- No Plan.") return None else: # Update Plan and Makespan plan = new_plan[0] self.plans[k] = plan self.makespan = max(plan[-1][0], self.makespan) self.makespan = sum([plan[-1][0] for plan in self.plans if plan != None]) print("- Feasible Plan Found with Makespan", plan[-1][0]) for j in self.higher_agents(k): self.collisions["%s-%s" % (k, j)] = "free" self.collisions["%s-%s" % (j, k)] = "free" # Unfreeze Collision Indicator for j in self.agents() - self.higher_agents(k): if "%s-%s" % (k, j) in self.collisions: self.collisions.pop("%s-%s" % (k, j)) if "%s-%s" % (j, k) in self.collisions: self.collisions.pop("%s-%s" % (j, k)) return plan <file_sep>/problems/zigzag/zigzag.py from util import * from problems.util import * A_rect = np.array([[-1,0], [1,0], [0,-1], [0,1]]) A_tri1 = np.array([[-1,-1], [1,-1], [0,1]]) A_tri2 = np.array([[-1,1], [1,1], [0,-1]]) b1 = np.array([[5], [20], [0]]) b2 = np.array([[-10], [35], [0]]) b3 = np.array([[-30], [0], [30]]) b4 = np.array([[-15], [-15], [30]]) b5 = np.array([[-45], [15], [30]]) b6 = np.array([[16], [51], [1], [0]]) b7 = np.array([[16], [51], [-30], [31]]) b8 = np.array([[16], [-15], [0], [30]]) b9 = np.array([[-50], [51], [0], [30]]) Obstacles = [(A_tri2, b1), (A_tri2, b2), (A_tri1, b3), (A_tri1, b4), (A_tri1, b5), (A_rect, b6), (A_rect, b7), (A_rect, b8), (A_rect, b9)] Thetas = [[40, 5], [40, 20], [-10, 5], [-10, 20]] Goals = [] pG1 = [-10, 20] lG1 = [2, 2] b1 = np.array([[-(pG1[0] - lG1[0])], [pG1[0] + lG1[0]], [-(pG1[1] - lG1[1])], [pG1[1] + lG1[1]]]) Goal1 = (A_rect, b1) Goals.append(Goal1) pG2 = [-10, 5] lG2 = [2, 2] b2 = np.array([[-(pG2[0] - lG2[0])], [pG2[0] + lG2[0]], [-(pG2[1] - lG2[1])], [pG2[1] + lG2[1]]]) Goal2 = (A_rect, b2) Goals.append(Goal2) pG3 = [40, 20] lG3 = [2, 2] b3 = np.array([[-(pG3[0] - lG3[0])], [pG3[0] + lG3[0]], [-(pG3[1] - lG3[1])], [pG3[1] + lG3[1]]]) Goal3 = (A_rect, b3) Goals.append(Goal3) pG4 = [40, 5] lG4 = [2, 2] b4 = np.array([[-(pG4[0] - lG4[0])], [pG4[0] + lG4[0]], [-(pG4[1] - lG4[1])], [pG4[1] + lG4[1]]]) Goal4 = (A_rect, b4) Goals.append(Goal4) limits = [[-16, 51], [-1, 31]] file_name = "problem.yaml" name = "zigzag" size = 1.5 velocity = 1 k = [0.5, 0.5, 0.5] agents = [Car(size, velocity, k) for _ in range(4)] write_problem(file_name, name, limits, Obstacles, agents, Thetas, Goals) <file_sep>/models/auv.py from math import * import numpy as np import random from scipy.integrate import odeint from models.agent import * from math import * import numpy as np from numpy.linalg import inv, norm class AUV(Agent): def __init__(self, size, velocity, k): self.size = size self.velocity = velocity self.k = k def model(self, q, t, u): # x, y, z, roll, pitch, yaw x, y, z, phi, theta, psi = q v = u[0] wx, wy, wz = u[1] xdot = v * cos(psi) * cos(theta) ydot = v * sin(psi) * cos(theta) zdot = v * sin(theta) phidot = wx + wy * sin(phi) * tan(theta) + wz * cos(phi) * tan(theta) thetadot = wy * cos(phi) - wz * sin(phi) psidot = wy * sin(phi) * (1 / cos(theta)) + wz * cos(phi) * (1 / cos(theta)) return [xdot, ydot, zdot, phidot, thetadot, psidot] def controller(self, q, qref, uref): x, y, z, phi, theta, psi = q c_phi = cos(phi) c_theta = cos(theta) c_psi = cos(psi) s_phi = sin(phi) s_theta = sin(theta) s_psi = sin(psi) k_1, k_2, k_3 = self.k R = np.array( [[c_psi * c_theta, c_psi * s_theta * s_phi - s_psi * c_phi, c_psi * s_theta * c_phi + s_psi * s_phi], [s_psi * c_theta, s_psi * s_theta * s_phi + c_psi * c_phi, s_psi * s_theta * c_phi - c_psi * s_phi], [-s_theta, c_theta * s_phi, c_theta * c_phi]]) B_2 = np.array([[1, sin(phi) * tan(theta), cos(phi) * tan(theta)], [0, cos(phi), -sin(phi)], [0, sin(phi) * (1 / cos(theta)), cos(phi) * (1 / cos(theta))]]) phi_d, theta_d, psi_d = qref[3:6] u_2d = np.array([[phi_d]]) v_d = uref[0] # The error is calculated here. This is the error between the waypoint and # the current state e_x, e_y, e_z, e_phi, e_theta, e_psi = calculate_error(q, qref, uref, R) u_2d = np.transpose(np.array(uref[1])) B_2d = np.array([[1, sin(phi_d) * tan(theta_d), cos(phi_d) * tan(theta_d)], [0, cos(phi_d), -sin(phi_d)], [0, sin(phi_d) * (1 / cos(theta_d)), cos(phi_d) * (1 / cos(theta_d))]]) Q = np.transpose(np.array([0, e_z * v_d / k_2, e_y * v_d * cos(e_theta) / k_3])) # te P_e = np.transpose(np.array([k_1 * sin(e_phi), k_2 * sin(e_theta), k_3 * sin(e_psi)])) # This is the control law gamma = 1 v_b = v_d * (cos(e_psi) * cos(e_theta) - 1) + e_x * gamma ** 2 u_2b = inv(B_2) * (Q + (B_2d - B_2) * u_2d + P_e) u_1 = v_d + v_b u_2 = u_2d + u_2b u_2 = [u_2[0][0], u_2[1][1], u_2[2][2]] return [u_1, u_2] def bloating(self, n): return 0 k1, k2, k3, kp = self.k if n != 0: return sqrt(4*n/k2) else: return 0 def run_model(self, q0, t, qref, uref): q = [q0] u0 = [0, [0, 0, 0]] for i in range(0, len(t)): t_step = [t[i - 1], t[i]] dx, dy, dz, dphi, dtheta, dpsi = [random.uniform(-0.001, 0.001), random.uniform(-0.001, 0.001), random.uniform(-0.001, 0.001), random.uniform(-0.001, 0.001), random.uniform(-0.001, 0.001), random.uniform(-0.001, 0.001)] q1 = odeint(self.model, q0, t_step, args=(u0,)) + [dx, dy, dz, dphi, dtheta, dpsi] q0 = q1[1] q.append(q0) u0 = self.controller(q0, qref[i], uref[i]) return q def calculate_error(q, qref, uref, R): X = np.array(q[0:3]) Theta = np.array(q[3:6]) # X_d = trajectory(t[idx], T, params) X_d = np.array(qref[0:3]) Theta_d = np.array(qref[3:6]) v_d = uref[0] wx,wy,wz = uref[1] X_e = np.transpose(R)*(X_d - X) Theta_e = Theta_d - Theta return [X_e[0][0], X_e[1][1], X_e[2][2], Theta_e[0], Theta_e[1], Theta_e[2]] <file_sep>/test.py from algs.decentralized import decentralized_algo from algs.ref2traj import ref2traj from problems.util import * from timeit import * from util import * from viz.plot import * from viz.animate import * from viz.util import * def test(env, problem_path, config_path): name, limits, Obstacles, agents, Thetas, Goals = read_problem(problem_path) min_segs, max_segs, obs_steps = read_configuration(config_path) start = default_timer() refs = decentralized_algo(agents, Thetas, Goals, limits, Obstacles, min_segs, max_segs, obs_steps, 0) end = default_timer() print("Total Time = ", end - start) name = '[%s]'%(env) trajs = ref2traj(refs) plot_results(agents, limits, Obstacles, Thetas, Goals, trajs, name, refs=refs) return refs test("zigzag", "problems/zigzag/problem.yaml", "problems/zigzag/config.yaml")<file_sep>/algs/ref2traj.py # Ref2Traj import numpy as np from numpy.linalg import norm def get_xref(p1, p2, times): dim = len(p1) t1, t2 = times[0], times[-1] if dim == 2: mx = p2[0] - p1[0] bx = p1[0] my = p2[1] - p1[1] by = p1[1] theta = np.arctan2((np.array(p2) - np.array(p1))[1], (np.array(p2) - np.array(p1))[0]) qref = [] # append the states to this list for time in times: xref = mx*((time - t1) / (t2 - t1)) + bx yref = my*((time - t1) / (t2 - t1)) + by qref.append([xref, yref, theta]) elif dim == 3: mx = p2[0] - p1[0] bx = p1[0] my = p2[1] - p1[1] by = p1[1] mz = p2[2] - p1[2] bz = p1[2] roll = 0 pitch = np.arctan2((np.array(p2) - np.array(p1))[2], norm(np.array(p2)[0:2] - np.array(p1)[0:2])) yaw = np.arctan2((np.array(p2) - np.array(p1))[1], (np.array(p2) - np.array(p1))[0]) qref = [] for time in times: xref = mx * ((time - t1) / (t2 - t1)) + bx yref = my * ((time - t1) / (t2 - t1)) + by zref = mz * ((time - t1) / (t2 - t1)) + bz qref.append([xref, yref, zref, roll, pitch, yaw]) else: print('Nodes not in workspace!') return qref def get_uref(p1, p2, times): dist = norm(np.array(p2) - np.array(p1)) v_ref = dist / (times[-1] - times[0]) dim = len(p1) if dim == 2: uref = [] for _ in times: vref = v_ref wref = 0 uref.append([vref, wref]) elif dim == 3: uref = [] for _ in times: vref = v_ref roll_ref = 0 pitch_ref = 0 yaw_ref = 0 uref.append([vref, [roll_ref, pitch_ref, yaw_ref]]) else: print('Nodes not in workspace!') return uref def ref2traj(ma_nodes): dim = len(ma_nodes[0][0])-1 agent_num = len(ma_nodes) # compute step size step_num = 10000 max_t = max([ma_nodes[idx][-1][0] for idx in range(agent_num)]) step_size = max_t / step_num ref_trajs = [] # calculate controller for idx in range(agent_num): ref_traj = [] nodes = ma_nodes[idx] for j in range(len(nodes) - 1): s1, s2 = nodes[j:j+2] t1, t2 = s1[0], s2[0] p1, p2 = s1[1:], s2[1:] times = np.arange(t1, t2, step_size) if times != []: qref = get_xref(p1, p2, times) uref = get_uref(p1, p2, times) ref_traj.append([times, qref, uref]) # keep still times = np.arange(ma_nodes[idx][-1][0], max_t, step_size) p = ma_nodes[idx][-1][1:] if times != []: qref = get_xref(p, p, times) uref = get_uref(p, p, times) ref_traj.append([times, qref, uref]) ref_trajs.append(ref_traj) return ref_trajs <file_sep>/models/agent.py class Agent: def __init__(self, size, velocity, k): self.size = size self.velocity = velocity self.k = k def model(self, q, t, u): pass def controller(self, q, qref, uref): pass def bloating(self, n): pass def run_model(self, q0, t, qref, uref): pass<file_sep>/viz/util.py from numpy import linalg import numpy as np from scipy.spatial import ConvexHull import mpl_toolkits.mplot3d as a3 import matplotlib.pyplot as plt import pypoman as ppm from shapely.geometry.polygon import Polygon from models.auv import * from models.hovercraft import * from util import * def plot_env(map_limits, Obstacles): fig = plt.figure() if len(map_limits) == 2: # Configure xmin, xmax = map_limits[0] ymin, ymax = map_limits[1] plt.xlim(xmin-2, xmax+2) plt.ylim(ymin-2, ymax+2) # # viz obstacles for A, b in Obstacles: poly = Polygon(ppm.duality.compute_polytope_vertices(A, b)) x, y = poly.exterior.xy plt.fill(x, y, facecolor='r', alpha=0.3) ax = fig.gca() plt.gca().set_aspect('equal', adjustable='box') plt.axis('off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) plt.margins(0, 0) elif len(map_limits) == 3: ax = fig.add_subplot(111, projection='3d') xmin, xmax = map_limits[0] ymin, ymax = map_limits[1] zmin, zmax = map_limits[2] ax.set_xlim3d(xmin, xmax) ax.set_ylim3d(ymin, ymax) ax.set_zlim3d(zmin, zmax) # set_equal TODO plt.axis('off') ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) ax.get_zaxis().set_visible(False) plt.margins(0, 0, 0) for obs in Obstacles: A, b = obs[0], obs[1] if len(A) == 4: A = np.array(A.tolist() + [[0, 0, -1], [0, 0, 1]]) b = np.array(b.tolist() + [[-map_limits[2][0]], [map_limits[2][1]]]) plot_polytope_3d(A, b, ax=ax, color='yellow', trans=0.2) return fig, ax def plot_goals(Goals): True for A, b in Goals: poly = Polygon(ppm.duality.compute_polytope_vertices(A, b)) x, y = poly.exterior.xy plt.fill(x, y, facecolor='g', alpha=0.3) def plot_thetas(thetas): for x, y in thetas: A, b = make_rectangle_center(x, y, 5, 5) poly = Polygon(ppm.duality.compute_polytope_vertices(A, b)) x, y = poly.exterior.xy plt.fill(x, y, facecolor='blue', alpha=0.3) def extract_paths(models, ma_thetas, ma_segs): # viz initial states and trajectories agent_num = len(models) paths = [] for idx in range(agent_num): theta = ma_thetas[idx] segs = ma_segs[idx] if len(theta) == 2: ref_x, ref_y, ref_theta, tru_x, tru_y, tru_theta, times = [], [], [], [], [], [], [] q0 = theta + [0] for seg in segs: t, qref, uref = seg ref_x = ref_x + [qref[i][0] for i in range(len(qref))] ref_y = ref_y + [qref[i][1] for i in range(len(qref))] ref_theta = ref_theta + [qref[i][2] for i in range(len(qref))] times = times + [t[i] for i in range(len(t))] run = models[idx].run_model q = run(q0, t, qref, uref) q0 = q[-1] tru_x = tru_x + [q[i][0] for i in range(len(q)-1)] tru_y = tru_y + [q[i][1] for i in range(len(q)-1)] tru_theta = tru_theta + [q[i][2] for i in range(len(q)-1)] paths.append([ref_x, ref_y, ref_theta, tru_x, tru_y, tru_theta, times]) elif len(theta) == 3: if isinstance(models[0], AUV): q0 = theta + [0, 0, 0] ref_x, ref_y, ref_z, times = [], [], [], [] tru_x, tru_y, tru_z, tru_thi, tru_theta, tru_psi = [], [], [], [], [], [] for seg in segs: t, qref, uref = seg ref_x = ref_x + [qref[i][0] for i in range(len(qref))] ref_y = ref_y + [qref[i][1] for i in range(len(qref))] ref_z = ref_z + [qref[i][2] for i in range(len(qref))] times = times + [t[i] for i in range(len(t))] run = models[idx].run_model q = run(q0, t, qref, uref) q0 = q[-1] tru_x = tru_x + [q[i][0] for i in range(len(q)-1)] tru_y = tru_y + [q[i][1] for i in range(len(q)-1)] tru_z = tru_z + [q[i][2] for i in range(len(q)-1)] tru_thi = tru_thi + [q[i][3] for i in range(len(q)-1)] tru_theta = tru_theta + [q[i][4] for i in range(len(q)-1)] tru_psi = tru_psi + [q[i][5] for i in range(len(q)-1)] paths.append([ref_x, ref_y, ref_z, tru_x, tru_y, tru_z, tru_thi, tru_theta, tru_psi, times]) elif isinstance(models[0], Hovercraft): q0 = theta + [0, 0, 0] ref_x, ref_y, ref_z, tru_x, tru_y, tru_z, times = [], [], [], [], [], [], [] for seg in segs: t, qref, uref = seg ref_x = ref_x + [qref[i][0] for i in range(len(qref))] ref_y = ref_y + [qref[i][1] for i in range(len(qref))] ref_z = ref_z + [qref[i][2] for i in range(len(qref))] times = times + [t[i] for i in range(len(t))] run = models[idx].run_model q = run(q0, t, qref, uref) q0 = q[-1] tru_x = tru_x + [q[i][0] for i in range(len(q)-1)] tru_y = tru_y + [q[i][1] for i in range(len(q)-1)] tru_z = tru_z + [q[i][2] for i in range(len(q)-1)] paths.append([ref_x, ref_y, ref_z, tru_x, tru_y, tru_z, times]) return paths class Faces(): def __init__(self,tri, sig_dig=12, method="convexhull"): self.method=method self.tri = np.around(np.array(tri), sig_dig) self.grpinx = list(range(len(tri))) norms = np.around([self.norm(s) for s in self.tri], sig_dig) _, self.inv = np.unique(norms,return_inverse=True, axis=0) def norm(self,sq): cr = np.cross(sq[2]-sq[0],sq[1]-sq[0]) return np.abs(cr/np.linalg.norm(cr)) def isneighbor(self, tr1,tr2): a = np.concatenate((tr1,tr2), axis=0) return len(a) == len(np.unique(a, axis=0))+2 def order(self, v): if len(v) <= 3: return v v = np.unique(v, axis=0) n = self.norm(v[:3]) y = np.cross(n,v[1]-v[0]) y = y/np.linalg.norm(y) c = np.dot(v, np.c_[v[1]-v[0],y]) if self.method == "convexhull": h = ConvexHull(c) return v[h.vertices] else: mean = np.mean(c,axis=0) d = c-mean s = np.arctan2(d[:,0], d[:,1]) return v[np.argsort(s)] def simplify(self): for i, tri1 in enumerate(self.tri): for j,tri2 in enumerate(self.tri): if j > i: if self.isneighbor(tri1,tri2) and \ self.inv[i]==self.inv[j]: self.grpinx[j] = self.grpinx[i] groups = [] for i in np.unique(self.grpinx): u = self.tri[self.grpinx == i] u = np.concatenate([d for d in u]) u = self.order(u) groups.append(u) return groups def plot_polytope_3d(A, b, ax = None, color = 'red', trans = 0.2): verts = np.array(ppm.compute_polytope_vertices(A, b)) # compute the triangles that make up the convex hull of the data points hull = ConvexHull(verts) triangles = [verts[s] for s in hull.simplices] # combine co-planar triangles into a single face faces = Faces(triangles, sig_dig=1).simplify() # viz if ax == None: ax = a3.Axes3D(plt.figure()) pc = a3.art3d.Poly3DCollection(faces, facecolor=color, edgecolor="k", alpha=trans) ax.add_collection3d(pc) # define view yllim, ytlim = ax.get_ylim() xllim, xtlim = ax.get_xlim() zllim, ztlim = ax.get_zlim() x = verts[:,0] x = np.append(x, [xllim, xtlim]) y = verts[:,1] y = np.append(y, [yllim, ytlim]) z = verts[:,2] z = np.append(z, [zllim, ztlim]) ax.set_xlim(np.min(x)-1, np.max(x)+1) ax.set_ylim(np.min(y)-1, np.max(y)+1) ax.set_zlim(np.min(z)-1, np.max(z)+1)
9a5b6a545c701af303519fd2d77fef1c4f23aa38
[ "Markdown", "Python" ]
21
Markdown
jian-dong/s2m2
b8e92eb6579d5e280e1fde1886a7f9829a590cef
a1a1dc25c8b059eb64b419e62d9e865fdd209add
refs/heads/master
<file_sep>a) $$ l(w) = \sum_{n=0}^{N-1}ln(1+e^{-y_nw^Tx_n}) $$ Where $w \in R^p, y \in \{-1;1\}, x \in R^p$ Find gradient w.r.t. "w" : $\frac{dl(w)}{dw}$ $$ \frac{dl(w)}{dw_1} = \sum_{n=0}^{N-1}\frac{e^{-y_nw^Tx_n}(-y_nx_1)}{1+e^{-y_nw^Tx_n}} $$ $$ \frac{dl(w)}{dw_2} = \sum_{n=0}^{N-1}\frac{e^{-y_nw^Tx_n}(-y_nx_2)}{1+e^{-y_nw^Tx_n}} $$ $$ \frac{dl(w)}{dw_i} = \sum_{n=0}^{N-1}\frac{e^{-y_nw^Tx_n}(-y_nx_i)}{1+e^{-y_nw^Tx_n}} $$ $$ \frac{dl(w)}{dw} = \sum_{n=0}^{N-1}\frac{e^{-y_nw^Tx_n}}{1+e^{-y_nw^Tx_n}}(-y_n) \begin{bmatrix} x_1 \\ x_2 \end{bmatrix} $$ b) $$ l(w) = \sum_{n=0}^{N-1}ln(1+e^{-y_nw^Tx_n}) + Cw^Tw $$ where $C\ge0$, regularization constant $$ \frac{dl(w)}{dw} = \sum_{n=0}^{N-1}\frac{e^{-y_nw^Tx_n}}{1+e^{-y_nw^Tx_n}}(-y_n) \vec{x} + 2C \vec{w} $$<file_sep># Exercise session 3 ## Pen&Paper tasks (written_tasks.pdf) * Pen&paper exercise. Classifying LDA manually * Pen&paper exercise. The answer was partly done in some other notebook so here is only answer. EX_Q2.pdf is the teachers answer to the task. ## Programming tasks * HomeWork3.ipynb - training classifiers (KNeighbor, LDA, SVC, LogReg) with digits-dataset using cross-validation * The last two tasks are classifying traffic signs. My implementation is in GSTRB_subset/traffic_signs.py <file_sep># -*- coding: utf-8 -*- """ Created on Tue Oct 22 14:08:03 2019 @author: Anton """ from scipy.io import loadmat import numpy as np import os def main(): os.chdir("Z:\Documents\TUT\Pattern Recognition and Machine Learning\Exercises\Ex1\Ex1_data") mat = loadmat("twoClassData.mat") X = mat['X'] y = mat['y'].ravel() x = X[y==0,:] xs = X[y==1,:] plt.plot(x[:,0],x[:,1],'ro') plt.plot(xs[:,0],xs[:,1],'bo') main()<file_sep># Exercise sessions Pattern Recognition and Machine Learning Here are all exercise tasks and answers of being in the header couse parly including pen&paper tasks. <file_sep>from sklearn.linear_model import LogisticRegression import os import numpy as np os.chdir('Z:\Documents\TUT\Pattern Recognition and Machine Learning\Exercises\Ex4') # 1) Load X and y. X = np.array(np.genfromtxt('X.csv',delimiter=',')) y = np.array(np.genfromtxt('y.csv')) # 2) Initialize w at w = np.array([1, -1]) w = np.array([1,-1]) # 3) Set step_size to a small positive value. step_size = 0.01 clf = LogisticRegression() clf.fit(X[:,np.newaxis],y) <file_sep># To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% import numpy as np import matplotlib.pyplot as plt from sklearn.discriminant_analysis import LinearDiscriminantAnalysis import scipy.stats as stats # %% mean1=np.array((1,1)).T cov1 = np.array(([1,0],[0,1])) x1,y1 = np.random.multivariate_normal(mean1,cov1,100).T plt.plot(x1,y1,'bo') mean2=np.array((3,3)).T cov2 = np.array(([2,0],[0,2])) x2,y2 = np.random.multivariate_normal(mean2,cov2,100).T plt.plot(x2,y2,'ro') #==================== temp1 = np.append(x1,x2) temp2 = np.append(y1,y2) X = np.vstack((temp1,temp2)).T y = np.vstack((np.zeros((100,1)),np.ones((100,1)))) clf = LinearDiscriminantAnalysis() clf.fit(X,y.ravel()) #print(clf.predict x = range(-2,6) yt = clf.coef_[0][0]*x + clf.coef_[0][1] plt.plot(x,yt,color='magenta') print(clf.intercept_) mCov = np.linalg.inv(cov1+cov2) print("mu",mean1.shape, "covariance", mCov.shape, "mu",mean1.T.shape) #c = -0.5*np.dot(mean2.T,mCov,mean2)+(0.5)*np.dot(mean1.T,mCov,mean2) #print("c =", c) #rint(mCov) <file_sep># -*- coding: utf-8 -*- """ Created on Sun Nov 17 13:47:06 2019 @author: Anton """ from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Activation, Flatten, MaxPooling2D, Conv2D from keras.utils import to_categorical import numpy as np import os (X_train, y_train), (X_test, y_test) = mnist.load_data() print(X_train.shape) # Keras assumes 4D input -> add a dummy axis !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! X_train = X_train[...,np.newaxis] /255.0 X_test = X_test[...,np.newaxis] /255.0 y_train = to_categorical(y_train) y_test = to_categorical(y_test) num_featmaps = 32 num_classes = 10 num_epochs = 20 w,h=5,5 model = Sequential() #Layer 1 model.add(Conv2D(num_featmaps,(w,h),input_shape=(28,28,1), activation='relu')) #Layer 2 model.add(Conv2D(num_featmaps,(w,h),activation='relu')) model.add(MaxPooling2D(pool_size=(2,2))) #Layer 3 #Flatten() vectorizes the data: 32x10x10 -> 3200 #(10x10 instead of 14x14 due to border effect) model.add(Flatten()) model.add(Dense(128,activation='relu')) #Layer 4 #Last layer producing outputs model.add(Dense(num_classes,activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) model.fit(X_train, y_train, epochs=num_epochs, validation_data=(X_test,y_test)) #https://machinelearningmastery.com/save-load-keras-deep-learning-models/ model.save('mnst.h5') ## load model #model = load_model('model.h5') ## summarize model. #model.summary() ## load dataset #dataset = loadtxt("pima-indians-diabetes.csv", delimiter=",") ## split into input (X) and output (Y) variables #X = dataset[:,0:8] #Y = dataset[:,8] ## evaluate the model #score = model.evaluate(X, Y, verbose=0) #print("%s: %.2f%%" % (model.metrics_names[1], score[1]*100))<file_sep># -*- coding: utf-8 -*- """ Created on Sun Dec 1 16:29:21 2019 @author: Anton """ from scipy.io import loadmat from sklearn.metrics import accuracy_score from sklearn.ensemble import RandomForestClassifier from sklearn.feature_selection import RFECV from sklearn.linear_model import LogisticRegression import matplotlib.pyplot as plt import numpy as np from sklearn.model_selection import cross_val_score import warnings warnings.filterwarnings('ignore') clf = LogisticRegression(penalty='l1') C_array = 10 ** np.arange(0,15,0.5) mat = loadmat('arcene\\arcene.mat') #print(mat.keys()) X_test = mat['X_test'] X_train = mat['X_train'] y_test = mat['y_test'].ravel() y_train = mat['y_train'].ravel() opt_c = 0 score = 0 for c in C_array: clf.C = c clf.fit(X_train, y_train) preds = clf.predict(X_test) #print('# of selected features:', clf.coef_) if np.mean(cross_val_score(clf, X_test, y_test)) > score: score = np.mean(cross_val_score(clf, X_test, y_test)) opt_c = c print('Max score:',score,'C-value:', opt_c) clf.C = opt_c clf.fit(X_train, y_train) f_selected = np.count_nonzero(clf.coef_) print('Features selected:',f_selected) print('Accuracy score:', np.mean(cross_val_score(clf,X_test,y_test)))<file_sep># -*- coding: utf-8 -*- """ Created on Sun Dec 1 16:29:21 2019 @author: Anton """ from scipy.io import loadmat from sklearn.metrics import accuracy_score from sklearn.ensemble import RandomForestClassifier from sklearn.feature_selection import RFECV from sklearn.linear_model import LogisticRegression import matplotlib.pyplot as plt import numpy as np clf = LogisticRegression() mat = loadmat('arcene\\arcene.mat') #print(mat.keys()) X_test = mat['X_test'] X_train = mat['X_train'] y_test = mat['y_test'].ravel() y_train = mat['y_train'].ravel() rfe = RFECV(estimator=clf, step=50, verbose=1) rfe.fit(X_train, y_train) selected = rfe.support_ print('Optimal # features:', np.sum(selected)) # 8600 plt.plot(range(0,10001,50),rfe.grid_scores_) plt.show() preds=rfe.predict(X_test) print('Accuracy is:',accuracy_score(preds,y_test)) #accuracy 0.84<file_sep># -*- coding: utf-8 -*- """ Created on Sun Nov 17 11:45:52 2019 @author: Anton """ import numpy as np from keras.models import Sequential from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense from keras.utils import np_utils from sklearn.model_selection import train_test_split import os N = 32 w,h = 5,5 X = np.load('gtsrb_X.npy') X = X[..., np.newaxis] / 255.0 y = np.load('gtsrb_y.npy') y = np_utils.to_categorical(y) print(X.shape) print(y.shape) X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2, random_state=42) model = Sequential() model.add(Conv2D(N,(w,h),input_shape=(64,64,1), activation='relu', padding='same')) model.add(MaxPooling2D(pool_size=(4,4))) model.add(Conv2D(N, (w,h), activation='relu',padding='same')) model.add(MaxPooling2D(pool_size=(4,4))) model.add(Flatten()) model.add(Dense(100,activation='relu')) model.add(Dense(2,activation='softmax')) print(model.summary()) model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) model.fit(X_train,y_train,epochs=20, batch_size=32 ,validation_data=(X_test,y_test))<file_sep># -*- coding: utf-8 -*- """ Created on Sun Oct 27 10:21:11 2019 @author: Anton """ import numpy as np import matplotlib.pyplot as plt import random import os from scipy.io import loadmat from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.discriminant_analysis import LinearDiscriminantAnalysis def main(): os.chdir("Z:\Documents\TUT\Pattern Recognition and Machine Learning\Exercises\Ex2\Ex1_data") mat = loadmat("twoClassData.mat") X = mat['X'] y = mat['y'].ravel() train, test, train_y, test_y = train_test_split(X,y,test_size=0.5) model = KNeighborsClassifier() model.fit(train,train_y) pred_y = model.predict(test) print(accuracy_score(test_y,pred_y)) model = LinearDiscriminantAnalysis() model.fit(train,train_y) model.fit(train,train_y) pred_y = model.predict(test) print(accuracy_score(test_y,pred_y)) main()<file_sep># Exercise session 1 * Maximum likelihood estimation tasks (1 and 2). Answer is in the ex1_written_task.pdf * Task3 - plotting data with pyplot * Task4 - removing uneven illumination in image using LSQR * Task5 - Practical estimating parameters of a sinusoid with python <file_sep># Exercese session 4 ## Pen&Paper tasks (written_tasks.pdf) * Computing gradient of the log-loss function * Drawing CNN from the given python code ## Programming exercises * task3.py - implementing gradient descent of the firts pen&paper task * keras_model_t4.py - editing given keras code * compiling network from the previous task and training on GTSRB (traffic signs) dataset <file_sep># Exercise session 2 * "Pen&paper" tasks were done on physical papers so here are no answers to the first three tasks * HomeWork2.ipynb - implementation of a sinusoid detector * HomeWork2.py - training the KNN and the LDA classifiers on test data <file_sep># -*- coding: utf-8 -*- """ Created on Sun Dec 1 12:09:33 2019 @author: Anton """ from scipy.io import loadmat from sklearn.ensemble import RandomForestClassifier import matplotlib.pyplot as plt import numpy as np clf = RandomForestClassifier(n_estimators=100) mat = loadmat('arcene\\arcene.mat') #print(mat.keys()) X_test = mat['X_test'] X_train = mat['X_train'] y_test = mat['y_test'].ravel() y_train = mat['y_train'].ravel() clf.fit(X_train, y_train) importancies=clf.feature_importances_ print(X_train.shape) #for f in range(X_train.shape[1]): # if importancies[indecies[f]] > 0.001: # print("%d. feature %d (%f)" % (f + 1, indecies[f], importancies[indecies[f]])) plt.figure() plt.title("Feature importances") #plt.bar(range(X_train.shape[1]), importancies[indecies], # color="r") plt.bar(np.arange(len(importancies)), importancies, color="r") plt.show() <file_sep> a) $$ l(w) = \sum_{n=0}^{N-1}ln(1+e^{-y_nw^Tx_n}) $$ Where $w \in R^p, y \in \{-1;1\}, x \in R^p$ Find gradient w.r.t. "w" : $\frac{dl(w)}{dw} \\$ My try is: $$ \begin{bmatrix} \frac{dl(w)}{dw_1} \\ \frac{dl(w)}{dw_2} \\ ... \\ \frac{dl(w)}{dw_n} \\ \end{bmatrix} = \begin{bmatrix} \sum_{n=0}^{N-1}\frac{-y_nx_ne^{-y_nw^Tx_n}}{1+e^{-y_nw^Tx_n}}x_1 \\ \sum_{n=0}^{N-1}\frac{-y_nx_ne^{-y_nw^Tx_n}}{1+e^{-y_nw^Tx_n}}x_2 \\ ... \\ \sum_{n=0}^{N-1}\frac{-y_nx_ne^{-y_nw^Tx_n}}{1+e^{-y_nw^Tx_n}}x_i \\ \end{bmatrix} $$ b) $$ l(w) = \sum_{n=0}^{N-1}ln(1+e^{-y_nw^Tx_n}) + C w^Tw $$ where $$ C \ge 0 $$ the regularization strength parameter Task is the same: find gradient of regularized log-loss function
a00112482afba61a09ec892c194feabb9fd424b4
[ "Markdown", "Python" ]
16
Markdown
blues-lead/ML_exercises
a6a9cb88eb7461d99cf8567b109bc390cf346d3e
16e95f83301a465cfb5fce29044e354d1c3414bc
refs/heads/master
<repo_name>shannonlu/DV_TProject1<file_sep>/DV_TProject2/03 R SQL Visualizations/CBB.R require("jsonlite") require("RCurl") require(ggplot2) require(dplyr) # The following is equivalent to KPI Story 2 Sheet 2 and Parameters Story 3 in "Crosstabs, KPIs, Barchart.twb" # These will be made to more resemble Tableau Parameters when we study Shiny. KPI_Low_Max_value = 3 KPI_Medium_Max_value = 7 df <- data.frame(fromJSON(getURL(URLencode(gsub("\n", " ", 'skipper.cs.utexas.edu:5001/rest/native/?query= "select * from CBB order by pos;" ')), httpheader=c(DB='jdbc:oracle:thin:@sayonara.microlab.cs.utexas.edu:1521:orcl', USER='C##cs329e_ba7433', PASS='<PASSWORD>', MODE='native_mode', MODEL='model', returnDimensions = 'False', returnFor = 'JSON', p1=KPI_Low_Max_value, p2=KPI_Medium_Max_value), verbose = TRUE))); View(df) #Produce fisrt bar chart, rotated on its side so you can actually read the conferences ggplot(df, aes(CONF, PTS, fill=CONF)) + geom_bar(stat="identity") + coord_flip() #Produce Second bar chart, rotated on its side so you can actually read the conferences ggplot(df, aes(CONF, PTS, fill=POS)) + geom_bar(stat="identity") + coord_flip() #PNN = Position Not NUll PNN <- df %>% filter(POS != "null") %>% tbl_df #Assist by Position ggplot() + coord_cartesian() + scale_x_continuous() + scale_y_continuous() + labs(title='Assists By Position') + labs(x="Minutes Played", y=paste("Assists")) + layer(data=PNN, mapping=aes(x=MP, y=AST, color=POS), stat="identity", stat_params=list(), geom="point", geom_params=list(), #position=position_identity() position=position_jitter(width=0.3, height=0) ) #Rebounds by Position ggplot() + coord_cartesian() + scale_x_continuous() + scale_y_continuous() + labs(title='Rebounds By Position') + labs(x="Minutes Played", y=paste("Total Rebounds")) + layer(data=PNN, mapping=aes(x=MP, y=TRB, color=POS), stat="identity", stat_params=list(), geom="point", geom_params=list(), #position=position_identity() position=position_jitter(width=0.3, height=0) ) #Steals by position ggplot() + coord_cartesian() + scale_x_continuous() + scale_y_continuous() + labs(title='Steals By Position') + labs(x="Personal Fouls", y=paste("Steals")) + layer(data=PNN, mapping=aes(x=as.numeric(as.character(PF)), y=as.numeric(as.character(STL)), color=POS), stat="identity", stat_params=list(), geom="point", geom_params=list(), #position=position_identity() position=position_jitter(width=0.3, height=0) ) #Blocks by Position ggplot() + coord_cartesian() + scale_x_continuous() + scale_y_continuous() + labs(title='Blocks By Position') + labs(x="Personal Fouls", y=paste("Blocks")) + layer(data=PNN, mapping=aes(x=as.numeric(as.character(PF)), y=as.numeric(as.character(BLK)), color=POS), stat="identity", stat_params=list(), geom="point", geom_params=list(), #position=position_identity() position=position_jitter(width=0.3, height=0) )
1c50e2296903c225f474dd866f5b9a4e3ab7dabd
[ "R" ]
1
R
shannonlu/DV_TProject1
33fa8c241df5d64926e039b735660630091623b0
21b96c6e6bc7e44758933f524803a6599b17b093
refs/heads/master
<file_sep>const express = require('express') const router = express.Router() const User = require('../models/User.model.js') const passport = require('passport') const ensureLoggedIn = (req, res, next) => req.isAuthenticated() ? next() : res.redirect('/login') const checkRole = role => (req, res, next) => req.isAuthenticated() && req.user.role.includes(role) ? next() : res.render('auth/login', { errorMsg: 'Restricted Zone' }) /* GET home page */ router.get('/', (req, res) => res.render('index', { user: req.user })) //Profile router.get('/profile', (req, res) => res.render('privates/profile', { user: req.user, canUpdate: true })) //UPDATE router.get('/update/:id', ensureLoggedIn, (req, res) => { User.findById(req.params.id) .then(foundUser => res.render('privates/update', { user: foundUser })) .catch(error => next(error)) }) router.post('/update/:id', ensureLoggedIn, (req, res) => { const { profileImg, name, description } = req.body User.findByIdAndUpdate(req.params.id, { profileImg, name, description }) .then(res.redirect('/profile')) .catch(error => next(error)) }) //READ router.get('/list-users', ensureLoggedIn, (req, res) => { User.find() .then(foundUsers => res.render('privates/users-list', { users: foundUsers })) .catch(error => next(error)) }) router.get('/profile/:id', (req, res) => { User.findById(req.params.id) .then(foundUser => res.render('privates/profile', { user: foundUser, canUpdate: false })) .catch(error => next(error)) }) //Delete router.get('/list-users/:id/delete', checkRole('BOSS'), (req, res, next) => { User.findByIdAndRemove(req.params.id) .then(res.redirect('/list-users')) .catch(error => next(error)) }) //BOSS UPDATE router.get('/update/:id/boss', checkRole('BOSS'), (req, res) => { User.findById(req.params.id) .then(foundUser => res.render('privates/update-boss', { user: foundUser })) .catch(error => next(error)) }) router.post('/update/:id/boss', checkRole('BOSS'), (req, res) => { const { profileImg, name, description, role } = req.body User.findByIdAndUpdate(req.params.id, { profileImg, name, description, role }, { new: true }) .then(updatedUser => res.redirect(`/profile/${updatedUser._id}`)) .catch(error => next(error)) }) module.exports = router <file_sep>const mongoose = require('mongoose') const User = require('../models/User.model') const bcrypt = require("bcrypt") const bcryptSalt = 10 const salt = bcrypt.genSaltSync(bcryptSalt) const dbName = 'passport-roles' mongoose.connect(`mongodb://localhost/${dbName}`, { useNewUrlParser: true, useUnifiedTopology: true }) const users = [ { username: 'boss1', name: 'Boss #1', password: <PASSWORD>('1', salt), profileImg: 'https://cdn.iconscout.com/icon/free/png-256/account-profile-avatar-man-circle-round-user-30452.png', description: 'It is a BOSS role user', facebookId: 'String', role: 'BOSS' }, { username: 'dev1', name: 'Dev #1', password: <PASSWORD>('1', salt), profileImg: 'https://cdn.iconscout.com/icon/free/png-256/account-profile-avatar-man-circle-round-user-30452.png', description: 'It is a DEV role user', facebookId: 'String', role: 'DEV' }, { username: 'dev2', name: 'Dev #2', password: <PASSWORD>Sync('2', salt), profileImg: 'https://cdn.iconscout.com/icon/free/png-256/account-profile-avatar-man-circle-round-user-30452.png', description: 'It is a DEV role user', facebookId: 'String', role: 'DEV' }, { username: 'ta1', name: `Teacher's Asistant #1`, password: <PASSWORD>.hashSync('1', salt), profileImg: 'https://cdn.iconscout.com/icon/free/png-256/account-profile-avatar-man-circle-round-user-30452.png', description: 'It is a TA role user', facebookId: 'String', role: 'TA' }, { username: 'ta2', name: `Teacher's Asistant #2`, password: <PASSWORD>Sync('2', salt), profileImg: 'https://cdn.iconscout.com/icon/free/png-256/account-profile-avatar-man-circle-round-user-30452.png', description: 'It is a TA role user', facebookId: 'String', role: 'TA' }, { username: 'student1', name: `Student #1`, password: <PASSWORD>('1', salt), profileImg: 'https://cdn.iconscout.com/icon/free/png-256/account-profile-avatar-man-circle-round-user-30452.png', description: 'It is a STUDENT role user', facebookId: 'String', role: 'STUDENT' } ] User.create(users) .then(theUsers => { console.log(`Next users were created: ${theUsers}`) mongoose.connection.close() }) .catch(error => next(error))
6217bceb974691efbb73f0a485bad8effdb1eec4
[ "JavaScript" ]
2
JavaScript
hectoranf/lab-passport-roles
4b1cb59ea167c4483b6118de5b711025df45eaf0
98893a176e9f35ea2e9bd05623296ee5542071b0
refs/heads/master
<repo_name>grg124/wallbreakers-training<file_sep>/week 1/reverseWordsInAStringIII.cpp class Solution { public: string reverseWords(string s) { int i=0; string ans; while(i<s.length()) { if(s.find(' ',i) ==std::string:: npos) { string sub; sub=sub+s.substr(i,s.length()-i); reverse(sub.begin(),sub.end()); ans=ans+sub; i=s.length(); } else if(s.find(' ',i) !=std::string:: npos) { int n=s.find(' ',i+1); string sub; sub=sub+s.substr(i,n-i); reverse(sub.begin(),sub.end()); ans=ans+sub+" "; i=n+1; } } return ans; } }; <file_sep>/week 1/twoSum.cpp class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int l=nums.size(); unordered_map <int,int> mp; for(int i=0;i<l;i++) { mp[nums[i]]=i; } vector<int> v; for(int i=0;i<l;i++) { int k=target-nums[i]; // if(nums[i]==k) continue; if( mp.find(k) != mp.end() && i!=mp[k]) { v.push_back(i); v.push_back(mp[k]); break; } } return v; } }; <file_sep>/week 2/isomorphicStrings.cpp class Solution { public: bool isIsomorphic(string s, string t) { int l=s.length(); unordered_map<char,char> a,b; for(int i=0;i<l;i++) { if(a.find(s[i])!=a.end() || b.find(t[i])!=b.end()) { if(a[s[i]]!=t[i] || b[t[i]]!=s[i]) { //cout<<b[t[i]]<<endl; // cout<<s[i]<<endl; return false; } } // else if(a.find(s[i])==a.end() && b.find(t[i])!=b.end()) // { // return false; // else if(b.find(t[i])==b.end() && a.find(s[i])!=a.end() ) // { // return false; // } else { a[s[i]]=t[i]; b[t[i]]=s[i]; } } return true; } }; <file_sep>/week 2/FindTheDifference.cpp class Solution { public: char findTheDifference(string s, string t) { int l=s.length(),k=t.length(); int hashs[26]={0},hasht[26]={0}; for(auto c:s) { hashs[c-'a']++; } for(auto c:t) { hasht[c-'a']++; } for(int i=0;i<26;i++) { if(hashs[i]!=hasht[i]) { return i+'a'; } } return '-1'; } }; <file_sep>/week 1/detectCapital.cpp class Solution { public: bool detectCapitalUse(string word) { int cap=0; for(int i=0;i<word.size();i++) { if(word[i]<='Z' && word[i]>='A') { cap++; } } if((cap==1 && word[0]<='Z' && word[0]>='A') || cap==0 || cap==word.length()) { return true; } return false; } }; <file_sep>/week 2/setMismatch.cpp const int ZERO = [](){ cin.tie(nullptr); ios_base::sync_with_stdio(false); return 0; }(); class Solution { public: vector<int> findErrorNums(vector<int>& nums) { int n=nums.size(); int hash[n]={0}; int sum=0; vector<int>v; for(auto c:nums) { hash[c-1]++; if(hash[c-1]==2) { v.push_back(c); } sum+=c; } v.push_back((n*(n+1))/2 -sum+v[0]); return v; } }; <file_sep>/week 3/valid_anagram.cpp static auto x = []{ std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return nullptr; }(); class Solution { public: bool isAnagram(string s, string t) { if(s.length()!=t.length()) return false; int l=s.length(); int a[26]={0}; for(auto c:s) { a[c-'a']++; } for(auto c:t) { a[c-'a']--; } for(auto f:a) { if(f!=0) return false; } return true; } }; <file_sep>/week 1/reverseString.cpp class Solution { public: void reverseString(vector<char>& s) { int l=s.size(); for(int i=0;i<l/2;i++) { swap(s[i],s[l-i-1]); } } }; <file_sep>/week 2/UncommonWordsFromTwoSentences.cpp class Solution { public: vector<string> uncommonFromSentences(string A, string B) { int a=A.length(),b=B.length(); unordered_map<string,int> cnta,cntb; int prev=-1,next; string k; for(int i=0;i<a;i++) { if(A[i]==' ') { cnta[k]++; k=""; } else { k.push_back(A[i]); } if(i==a-1) { cnta[k]++; k=""; } } for(int i=0;i<b;i++) { if(B[i]==' ') { cntb[k]++; k=""; } else { k.push_back(B[i]); } if(i==b-1) { cntb[k]++; k=""; } } vector<string> g; for(auto i:cnta) { if(i.second==1 && cntb.find(i.first)== cntb.end()) { g.push_back(i.first); } } for(auto i:cntb) { if(i.second==1 && cnta.find(i.first)== cnta.end()) { g.push_back(i.first); } } return g; } }; <file_sep>/week 3/array_partition_1.cpp class Solution { public: int arrayPairSum(vector<int>& nums) { sort(nums.begin(),nums.end()); int n=nums.size(),sum=0; for(int i=0;i<n;i=i+2) { sum=sum+nums[i]; } return sum; } }; <file_sep>/week 2/UniqueMorseCodeWords.cpp class Solution { public: int uniqueMorseRepresentations(vector<string>& words) { string s[26]={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."}; unordered_set<string> g; for(auto w:words) { string r; for(auto c:w) { r+=s[c-'a']; // r.push_back(s[c-'a']); } g.insert(r); } return g.size(); } }; <file_sep>/week 2/jewelsAndStone.cpp class Solution { public: int numJewelsInStones(string J, string S) { int lj=J.length(),ls=S.length(),count=0; for(int i=0;i<lj;i++) { for(int j=0;j<ls;j++) { if(J[i]==S[j]) { count++; } } } return count; } }; <file_sep>/week 2/happyNumbers.cpp class Solution { public: int sqdig(int n) { int sum=0; while(n>0) { int r=n%10; sum+=r*r; n=n/10; } return sum; } bool isHappy(int n) { bool repeat=false; unordered_set<int>v; v.insert(n); while(repeat==false) { if(n==1) { return true; } int prevsize=v.size(); n=sqdig(n); v.insert(n); int newsize=v.size(); if(prevsize==newsize) { return false; } } return false; } }; <file_sep>/week 2/DistributeCandies.cpp class Solution { public: int distributeCandies(vector<int>& candies) { unordered_map<int,int>mp; int n=candies.size(); for(int i=0;i<n;i++) { mp[candies[i]]++; } int t=mp.size(); if(t<=n/2) { return t; } return n/2; } }; <file_sep>/week 1/validAnagram.cpp class Solution { public: bool isAnagram(string s, string t) { if(s.length()!=t.length()) return false; int hashs[26],hasht[26]; memset(hashs,0,sizeof(hashs)); memset(hasht,0,sizeof(hasht)); for(int i=0;i<s.size();i++) { hashs[s[i]-'a']++; } for(int i=0;i<t.size();i++) { hasht[t[i]-'a']++; } for(int i=0;i<26;i++) { if(hashs[i]!=hasht[i]) { return false; } } return true; } }; <file_sep>/week 1/selfDividingNumbers.cpp class Solution { public: bool selfdiv(int n) { int k=n; while(k>0) { int r=k%10; if(r==0 || n%r!=0) return false; k=k/10; } return true; } vector<int> selfDividingNumbers(int left, int right) { vector <int> vc; for(int i=left;i<=right;i++) { if(selfdiv(i)) { vc.push_back(i); } } return vc; } }; <file_sep>/week 1/singleNumber.cpp class Solution { public: int singleNumber(vector<int>& nums) { int l=nums.size(),x=0; for(int i=0;i<l;i++) { x=x^nums[i]; } return x; } }; <file_sep>/week 1/fizzBuzz.cpp class Solution { public: vector<string> fizzBuzz(int n) { vector <string > vc; map <int ,string> m; m[3]="Fizz"; m[5]="Buzz"; for(int i=1;i<=n;i++) { string s; for(auto j:m) { if(i%(j.first)==0) { s+=(j.second); } } if(s.length()==0) { s+=to_string(i); } vc.push_back(s); } return vc; } }; <file_sep>/README.md # wallbreakers-training 3 Week DS algo + 3 week (Soft skills + mock interview + tech skills) <file_sep>/week 1/hammingDistance.cpp class Solution { public: int hammingDistance(int x, int y) { int i,count=0; for(int i=0;i<31;i++) { if(((1<<i)&x) != ((1<<i)&y)) { count++; } } return count; } }; <file_sep>/week 2/intersectionOfTwoArray.cpp class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { int l1=nums1.size(),l2=nums2.size(); int m=min(l1,l2); vector<int> v; unordered_set <int> s; if(l1==m) { for(auto i: nums1) { s.insert(i); } sort(nums2.begin(),nums2.end()); for(auto i:s) { if(binary_search(nums2.begin(),nums2.end(),i)) { v.push_back(i); } } } else { for(auto i: nums2) { s.insert(i); } sort(nums1.begin(),nums1.end()); for(auto i:s) { if(binary_search(nums1.begin(),nums1.end(),i)) { v.push_back(i); } } } return v; } }; <file_sep>/week 1/excelSheetColumnNumber.cpp class Solution { public: // for length l=1 ->26^0 // l=2 -> 26^1+26^0 // l=3 ->26^2 +26^1 +26^0 // by current string sum(s[i]*26^(n-i-1)) from 0 to s.length() int cal(int n) { int sum=0; for(int i=0;i<n;i++) { sum=sum+pow(26,i); } return sum; } int titleToNumber(string s) { int l=s.length(); int sum=cal(l); for(int i=0;i<l;i++) { sum=sum+(s[i]-'A')*pow(26,l-i-1); } return sum; } }; <file_sep>/week 2/firstUniqueCharacterInString.cpp static auto x = [](){ std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return nullptr; }(); class Solution { public: int firstUniqChar(string s) { int l=s.length(); int mp[26]={0}; for(int i=0;i<l;i++) { mp[s[i]-'a']++; } for(int i=0;i<l;i++) { if(mp[s[i]-'a']==1) { return i; } } return -1; } }; <file_sep>/week 1/FlippingAnImage.cpp class Solution { public: vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) { int n=A.size(),m=A[0].size(); vector<vector<int>> out( n , vector<int> (m)); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(A[i][j]==1) { out[i][m-j-1]=0; } else { out[i][m-j-1]=1; } } } return out; } }; <file_sep>/week 1/transposeMatrix.cpp class Solution { public: vector<vector<int>> transpose(vector<vector<int>>& A) { int n=A.size(),m=A[0].size(); vector <vector<int>> mat; for(int j=0;j<m;j++) { vector<int> row; for(int i=0;i<n;i++) { row.push_back(A[i][j]); } mat.push_back(row); } return mat; } };
db6a4149c2331c0904ca877239095d796f7c7707
[ "Markdown", "C++" ]
25
C++
grg124/wallbreakers-training
1ecac473db62c9799e4682954a90016134a79d41
f09c230d465b305fe2555829fb06097ddf3a3168
refs/heads/master
<repo_name>Shivamkshiv/KurtisGallery_1<file_sep>/app/src/main/java/developers/findingcodes/kurtisgallery/SlideshowDialogFragment.java package developers.findingcodes.kurtisgallery; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.ContactsContract; import android.support.v4.app.DialogFragment; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.squareup.picasso.Picasso; import com.squareup.picasso.Target; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Date; //import android.widget.Toolbar; public class SlideshowDialogFragment extends DialogFragment { private String TAG = SlideshowDialogFragment.class.getSimpleName(); private ArrayList<Image> images; private ViewPager viewPager; private MyViewPagerAdapter myViewPagerAdapter; private TextView lblCount, lblTitle, lblDate; private int selectedPosition = 0; private ProgressBar progressBar; private ImageView imageView; private TextView downloadImage; private TextView shareImage; private Toolbar toolbar; static SlideshowDialogFragment newInstance() { SlideshowDialogFragment f = new SlideshowDialogFragment(); return f; } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_image_slider, container, false); toolbar = (Toolbar) v.findViewById(R.id.toolbar); progressBar = (ProgressBar) v.findViewById(R.id.progressBar); downloadImage = (TextView) v.findViewById(R.id.downloadone); shareImage = (TextView) v.findViewById(R.id.sharewhatsapp); // // // set the listener for Navigation // Toolbar actionBar = (Toolbar) v.findViewById(R.id.fake_action_bar); // if (actionBar!=null) { // final SlideshowDialogFragment window = this; // actionBar.setTitle("knfkdnf"); // actionBar.setNavigationOnClickListener(new View.OnClickListener() { // public void onClick(View v) { // window.dismiss(); // } // }); // } viewPager = (ViewPager) v.findViewById(R.id.viewpager); lblCount = (TextView) v.findViewById(R.id.lbl_count); // lblTitle = (TextView) v.findViewById(R.id.title); //lblDate = (TextView) v.findViewById(R.id.date); images = (ArrayList<Image>) getArguments().getSerializable("images"); selectedPosition = getArguments().getInt("position"); Log.e(TAG, "position: " + selectedPosition); Log.e(TAG, "images size: " + images.size()); myViewPagerAdapter = new MyViewPagerAdapter(); viewPager.setAdapter(myViewPagerAdapter); viewPager.addOnPageChangeListener(viewPagerPageChangeListener); setCurrentItem(selectedPosition); return v; } private void setCurrentItem(int position) { viewPager.setCurrentItem(position, false); displayMetaInfo(selectedPosition); } // page change listener ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() { @Override public void onPageSelected(int position) { displayMetaInfo(position); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }; private void displayMetaInfo(int position) { lblCount.setText((position + 1) + " of " + images.size()); Image image = images.get(position); // lblTitle.setText(image.getLarge()); final String imgsrc =image.getLarge(); downloadImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { downloadImage(imgsrc); } }); //lblDate.setText(image.getTimestamp()); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar_Fullscreen); setStyle(DialogFragment.STYLE_NO_FRAME, android.R.style.Theme_Holo_Light_DarkActionBar); } // adapter public class MyViewPagerAdapter extends PagerAdapter { private LayoutInflater layoutInflater; public MyViewPagerAdapter() { } @Override public Object instantiateItem(ViewGroup container, int position) { layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = layoutInflater.inflate(R.layout.image_fullscreen_preview, container, false); imageView = (ImageView) view.findViewById(R.id.image_preview); Image image = images.get(position); Glide.with(getActivity()).load(image.getLarge()) .thumbnail(0.5f) .crossFade() .diskCacheStrategy(DiskCacheStrategy.ALL) .into(imageView); progressBar.setVisibility(View.INVISIBLE); shareImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //shareImage(); // ImageView iv = (ImageView) view.findViewById(viewPager.getCurrentItem()); Log.e(TAG, "IMAGEs " +imageView); //Uri bmpUri = getLocalBitmapUri(imageView); Drawable drawable = imageView.getDrawable(); Bitmap bmp = null; if (drawable instanceof BitmapDrawable) bmp = ((BitmapDrawable)drawable).getBitmap(); else { Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); bmp = bitmap; Log.e(TAG, "IMAGEs " +bmp); } Uri bmpUri = null; try { File file = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png"); file.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(file); Log.e(TAG, "popopo: " + file); bmp.compress(Bitmap.CompressFormat.PNG, 90, out); out.close(); bmpUri = Uri.fromFile(file); } catch (IOException e) { e.printStackTrace(); } if (bmpUri != null) { // Construct a ShareIntent with link to image Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri); shareIntent.setType("image/*"); shareIntent.setPackage("com.whatsapp"); shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // Launch sharing dialog for image startActivity(Intent.createChooser(shareIntent, "Share Image")); } else { // ...sharing failed, handle error Log.e(TAG, "<NAME>" + bmpUri); } } }); imageView.setId(position); container.addView(view); return view; } @Override public int getCount() { return images.size(); } @Override public boolean isViewFromObject(View view, Object obj) { return view == ((View) obj); } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } } public void downloadImage(String imgloc) { String img_url = images.get(selectedPosition).getLarge(); Log.e(TAG, "BABAB" + imgloc); Picasso.with(getActivity()) .load(imgloc) .into(new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { try { String root = Environment.getExternalStorageDirectory().toString(); File myDir = new File(root + "/kurtis"); if (!myDir.exists()) { myDir.mkdirs(); } String name = new Date().toString() + ".jpg"; myDir = new File(myDir, name); FileOutputStream out = new FileOutputStream(myDir); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); Toast.makeText(getActivity(), "Download Completed", Toast.LENGTH_SHORT).show(); getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); } catch (Exception e) { // some action } } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } } ); } public Uri getLocalBitmapUri(ImageView imageView) { // Extract Bitmap from ImageView drawable Log.v(TAG,"IMAGEJI "+imageView); //iv.setDrawingCacheEnabled(true); Drawable drawable = imageView.getDrawable(); Bitmap bmp = null; if (drawable instanceof BitmapDrawable) { bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap(); } else { return null; } // Store image to default external storage directory Uri bmpUri = null; try { File file = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png"); file.getParentFile().mkdirs(); FileOutputStream out = new FileOutputStream(file); Log.e(TAG, "popopo: " + file); bmp.compress(Bitmap.CompressFormat.PNG, 90, out); out.close(); bmpUri = Uri.fromFile(file); } catch (IOException e) { e.printStackTrace(); } return bmpUri; } }<file_sep>/app/src/main/java/developers/findingcodes/kurtisgallery/FragmentNewArrival.java package developers.findingcodes.kurtisgallery; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.GridView; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.squareup.picasso.Picasso; import com.squareup.picasso.Target; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class FragmentNewArrival extends Fragment implements LoaderManager.LoaderCallbacks<List<Image>> { private String TAG = MainActivity.class.getSimpleName(); private static final String IMAGE_URL = "https://developers.kurtisgallery.in/example_api/kurtisone/id/10"; private ArrayList<Image> lists; private GalleryAdapter mAdapter; private RecyclerView recyclerView; ImageView downloadimg; ImageView whatsappShare; private ProgressBar mProgressBar; private static final int IMAGE_LOADER_ID = 1; public FragmentNewArrival() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_akpremium_one, container, false); Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar); whatsappShare= (ImageView) rootView.findViewById(R.id.whatsappsharebtn); mProgressBar = (ProgressBar) rootView.findViewById(R.id.progressBar1); //setSupportActionBar(toolbar); //setSupportActionBar(toolbar); recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view); recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getActivity(), recyclerView, new GalleryAdapter.ClickListener() { @Override public void onClick(View view, int position) { Bundle bundle = new Bundle(); bundle.putSerializable("images", lists); bundle.putInt("position", position); FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction(); SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance(); newFragment.setArguments(bundle); newFragment.show(ft, "slideshow"); } @Override public void onLongClick(View view, int position) { } })); downloadimg = (ImageView) rootView.findViewById(R.id.downloadall); downloadimg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String[] urls = new String[50]; for (int i = 0; i < lists.size(); i++) { urls[i] = lists.get(i).getSmall(); } DownloadImages downloadImages= new DownloadImages(); downloadImages.downloadImage(getActivity(),urls); Toast.makeText(getActivity(),"Images Saved successfully",Toast.LENGTH_LONG).show(); } }); whatsappShare.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ShareImages(); } }); return rootView; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Get a reference to the ConnectivityManager to check state of network connectivity ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); // Get details on the currently active default data network NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); // If there is a network connection, fetch data if (networkInfo != null && networkInfo.isConnected()) { // Get a reference to the LoaderManager, in order to interact with loaders. LoaderManager loaderManager = getLoaderManager(); // Initialize the loader. Pass in the int ID constant defined above and pass in null for // the bundle. Pass in this activity for the LoaderCallbacks parameter (which is valid // because this activity implements the LoaderCallbacks interface). loaderManager.initLoader(IMAGE_LOADER_ID, null, this); } } private void ShareImages(){ Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND_MULTIPLE); intent.putExtra(Intent.EXTRA_SUBJECT, "Here are some files."); intent.setType("image/*"); /* This example is sharing jpeg images. */ intent.setPackage("com.whatsapp"); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); final ArrayList<Uri> files = new ArrayList<>(); for(int i=0;i<lists.size();i++){ String img_url = lists.get(i).getLarge(); Picasso.with(getContext()).load(img_url).into(new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { Uri uri = getImageUri(getContext(),bitmap); files.add(uri); } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } }); } intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files); // startActivity(Intent.createChooser(intent, "Share Image")); startActivity(intent); } public Uri getImageUri(Context inContext, Bitmap inImage) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null); return Uri.parse(path); } @Override public Loader<List<Image>> onCreateLoader(int i, Bundle bundle) { // Create a new loader for the given URL return new ImageLoader(getContext(), IMAGE_URL); } @Override public void onLoadFinished(Loader<List<Image>> loader, List<Image> images) { lists = new ArrayList<>(); try{ for(int i=0;i<images.size();i++){ String small = images.get(i).getSmall(); String large = images.get(i).getLarge(); Image image = new Image(small,large); lists.add(image); } }catch (NullPointerException e){ Log.e(TAG,"ASDFG",e); } mProgressBar.setVisibility(View.INVISIBLE); mAdapter = new GalleryAdapter(getActivity(), lists); RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(mAdapter); } @Override public void onLoaderReset(Loader<List<Image>> loader) { // Loader reset, so we can clear out our existing data. recyclerView.setAdapter(null); } } <file_sep>/app/src/main/java/developers/findingcodes/kurtisgallery/DownloadImages.java package developers.findingcodes.kurtisgallery; import android.content.ContentValues; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.media.MediaScannerConnection; import android.os.Environment; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; import com.squareup.picasso.Picasso; import com.squareup.picasso.Target; import java.io.File; import java.io.FileOutputStream; import java.util.Date; public class DownloadImages extends AppCompatActivity { public void downloadImage(final Context ctx, String[]imgloc) { for (int i = 0; i < imgloc.length; i++) { Picasso.with(ctx) .load(imgloc[i]) .into(new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { try { String root = Environment.getExternalStorageDirectory().toString(); File myDir = new File(root + "/~AK KurtisGallery"); if (!myDir.exists()) { myDir.mkdirs(); } String name = new Date().getTime() + ".jpg"; myDir = new File(myDir, name); FileOutputStream out = new FileOutputStream(myDir); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); Log.i("TAG", "scanning File " +myDir.getAbsolutePath()); MediaScannerConnection.scanFile(getBaseContext(), new String[]{myDir.getAbsolutePath()}, null, null); Toast.makeText(ctx, "Download Completed", Toast.LENGTH_SHORT).show(); // sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(myDir))); Log.i("TAG", "Agter scanning" +myDir.getAbsolutePath()); } catch (Exception e) { // some action } //sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory()))); } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } } ); } } private void scanFile(String path) { ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DATA,""+path); values.put(MediaStore.Images.Media.MIME_TYPE,"image/jpeg"); getApplicationContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values); Log.i("TAG", "Agter scanning" +path); } } <file_sep>/app/src/main/java/developers/findingcodes/kurtisgallery/AsSeriesFragment.java package developers.findingcodes.kurtisgallery; import android.support.v4.app.Fragment; public class AsSeriesFragment extends Fragment { } <file_sep>/app/src/main/java/developers/findingcodes/kurtisgallery/ImageLoader.java package developers.findingcodes.kurtisgallery; import android.support.v4.content.AsyncTaskLoader; import android.content.Context; import java.util.List; public class ImageLoader extends AsyncTaskLoader<List<Image>> { private String mUrl; List<Image> images; private List<Image> CachedData; public ImageLoader(Context context, String url){ super(context); mUrl = url; } public ImageLoader(Context context) { super(context); } @Override protected void onStartLoading() { if(CachedData == null){ forceLoad(); }else{ super.deliverResult(CachedData); } } @Override public List<Image> loadInBackground() { if(mUrl == null){ return null; } QueryUtils queryUtils = new QueryUtils(); images = queryUtils.fetchImageData(mUrl); return images; } @Override public void deliverResult(List<Image> data) { CachedData = data; super.deliverResult(data); } }
720b974f5d24f93aa4a433c5630c4ff29c25a7cf
[ "Java" ]
5
Java
Shivamkshiv/KurtisGallery_1
671cb774fc2ea2a381ce2247c89150f6eb3d4ad0
3908ea0a21c7898f12ebeb40cfcaa82c8952075c
refs/heads/master
<repo_name>AndrewKeig/grunt-elasticsearch-bulk<file_sep>/Gruntfile.js 'use strict'; module.exports = function(grunt) { grunt.loadTasks('./tasks'); grunt.initConfig({ elasticsearchbulk: { files: { src : ['data/user.json', 'data/role.json'] }, options: { elastic: { host: "http://127.0.0.1:9200", client: { apiVersion: "1.0", log: "info" } } } } }); };<file_sep>/README.md # grunt-elasticsearch-bulk Grunt task for working with the elasticsearch bulk api ## Getting Started This plugin requires Grunt `~0.4.1 If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command: ``` npm install grunt-elasticsearch-bulk --save-dev ``` Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript: ``` grunt.loadNpmTasks('grunt-elasticsearch-bulk'); ``` ## The elasticsearchbulk task ### Overview In your project's Gruntfile, add a section named `elasticsearchbulk` to the data object passed into `grunt.initConfig()`. ``` grunt.initConfig({ elasticsearchbulk: { src: { src : ['data/user.json', 'data/role.json'] }, options: { elastic: { host: "http://127.0.0.1:9200", client: { apiVersion: "1.0", log: "info" } } } } }); ``` ## Options grunt-elasticsearch-bulk uses `elasticsearch.js`; so simply provide the options used there; where relevant for bulk api: http://www.elasticsearch.org/guide/en/elasticsearch/client/javascript-api/current/configuration.html <file_sep>/tasks/index.js 'use strict'; var _ = require('lodash'); var elastic = require('elasticsearch'); var async = require('async'); module.exports = function(grunt) { grunt.registerMultiTask("elasticsearchbulk", "Grunt task for working with the elasticsearch bulk api", function() { var done = this.async(); var options = this.options(); var files = this.filesSrc; var defaults = { elastic : { host: 'http://127.0.0.1:9200', client: { apiVersion: "1.0", log: "warning" } } }; var options = _.extend(defaults, options); var client = new elastic.Client(options); async.eachSeries(files, function(file, callback){ grunt.log.ok('starting elastic search bulk for ', file); var data = grunt.file.readJSON(file); client.bulk({ body: data }, function(err){ if (err) { grunt.fail.warn('Unable to connect to elastic search'); } if (!err) { grunt.log.ok('elastic search bulk run complete.'); } callback(); }); }, function(err){ if (err) return done(false); process.nextTick(done); }); }); };
379219e27cfbd51c598c91731ba41d058ae8958e
[ "JavaScript", "Markdown" ]
3
JavaScript
AndrewKeig/grunt-elasticsearch-bulk
2e4ef01463ef7e7d0a1221dd507c9f7f5402f0cd
cdd18285d310f316b2eb812f1389b1815eb294b1
refs/heads/master
<file_sep>#ifndef BST_HPP #define BST_HPP #include "BSTNode.hpp" #include "BSTIterator.hpp" #include <utility> // for std::pair template<typename Data> class BST { protected: /** Pointer to the root of this BST, or nullptr if the BST is empty */ BSTNode<Data>* root; /** Number of Data items stored in this BST. */ unsigned int isize; public: /** iterator is an aliased typename for BSTIterator<Data>. */ typedef BSTIterator<Data> iterator; /** Default constructor. Initialize an empty BST. */ BST() : root(nullptr), isize(0) { } /** Default destructor. * It is virtual, to allow appropriate destruction of subclass objects. * Delete every node in this BST. */ // TODO virtual ~BST() { this->clear(); //delete every node in BST } /** Insert a Data item in the BST. * Return a pair, with the pair's first member set to an * iterator pointing to either the newly inserted element * or to the equivalent element already in the set. * The pair's second element is set to true * if a new element was inserted or false if an * equivalent element already existed. */ // TODO virtual std::pair<iterator,bool> insert(const Data& item) { BSTNode<Data> *p = root, *prev = nullptr; while(p!= nullptr){ //find a place for inserting new node prev = p; if (item < p->data) // element smaller than current node' key p = p->left; // p point to current node's left children else if (item > p->data) //element larger than current node's key p = p->right; //p point to current node's left children else p=nullptr; // item equals current node's key } if (root == nullptr) { // if tree is empty root = new BSTNode<Data>(item); return std::make_pair(iterator(root), 1); } else if (item < prev->data) { // item smaller than prev'data, insert in its left node prev->left = new BSTNode<Data>(item); isize++; return std::make_pair(iterator(prev->left), 1); } else if (item > prev->data){ //item larger than prev's data, insert in its right node prev->right = new BSTNode<Data>(item); isize++; return std::make_pair(iterator(prev->right), 1); } else return std::make_pair(iterator(prev), 0); // item equal prev's data, return false } /** Find a Data item in the BST. * Return an iterator pointing to the item, or the end * iterator if the item is not in the BST. */ // TODO iterator find(const Data& item) const { BSTNode<Data>* p = root; while(p!=nullptr){ if (item < p->data ) p = p->left; else if (item > p->data) p = p->right; else if (item == p->data) return typename BST<Data>::iterator(p); } return this->end();//item is not in the BST } /** Return the number of items currently in the BST. */ // TODO unsigned int size() const { return isize; } /** Remove all elements from this BST, and destroy them, * leaving this BST with a size of 0. */ // TODO void clear() { BSTNode<Data> *q[isize]; // define an pointer array BSTNode<Data> *p = root, *prev = nullptr; while (p != nullptr) { // if p is not null prev = p; p = p->left; } for (int i = 0; i < isize; i++) { q[i] = prev; prev = prev->successor(); } for (int i = 0; i < isize; i++) { delete q[i]; // delete q[i] q[i] = nullptr; // q[i] points to null } isize = 0; // assign 0 to isize } /** Return true if the BST is empty, else false. */ // TODO bool empty() const { if (isize==0) return 1; else return 0; } /** Return an iterator pointing to the first item in the BST. */ // TODO iterator begin() const { BSTNode<Data>*p = root, *prev = nullptr; while (p!=nullptr){ prev = p; p = p->left; } return typename BST<Data>::iterator(prev); } /** Return an iterator pointing past the last item in the BST. */ iterator end() const { return typename BST<Data>::iterator(nullptr); } }; #endif //BST_HPP
a628e88db95c32ea09f3d47a2bedd8d2ae6e8558
[ "C++" ]
1
C++
yaqingwang/Binary-Search-Tree
6a0b12a8ea2146478451c59c2f7da57ca8a35f1e
1227ede32ad866040727e67a22bea00f6314ee0e
refs/heads/master
<repo_name>pedrera/ProgrammingAssignment2<file_sep>/cachematrix.R ## Put comments here that give an overall description of what your ## functions do # makeCacheMatrix creates one matrix object with the methods: # get matrix # set matrixParam to matrix # get matrix inverse # set inverseParam to matrix inverse makeCacheMatrix <- function(x = matrix()) { inverseMatrix <- NULL get <- function() x set <- function(matrixParam) { x <<- matrixParam inverseMatrix <<- NULL } getInverse <- function() inverseMatrix setInverse <- function(inverseParam) { inverseMatrix <<- inverseParam } list(get=get, set=set, getInverse=getInverse, setInverse=setInverse) } # cacheSolve calculates the inverse of a matrix. cacheSolve <- function(x, ...) { inverseMatrix <- x$getInverse() ## Inverse Matrix Calculation only If inverseMatrix is null if(is.null(inverseMatrix)) { inverseMatrix <- solve(x$get()) x$setInverse(inverseMatrix) } inverseMatrix }
ede1bdc5fd8757c30713c13df806bcd7b9388caa
[ "R" ]
1
R
pedrera/ProgrammingAssignment2
a119240adbbee88dc9de65b8085a3cc1493805b7
a50914788b212a78f8679402bb76ec6baa1e10e4
refs/heads/master
<file_sep>import networkx as nx import numpy as np import matplotlib.pyplot as plt ''' This is an example of the very first relation that Wolfram presents as an example: {(x, y), (x, z)} -> {(x, z), (x, w), (y, w), (z, w)} Currently tweaking script to make it more general - general.py ''' # Maximum iterations ITERATIONS = 100 # Initializes graph G = nx.Graph() G.add_edge(1, 2) G.add_edge(2, 3) G.add_edge(3, 4) G.add_edge(2, 4) c = 0 run = True print(G.edges) edges = list(G.edges) print(edges[0]) # Cleans up input of relations def clean(): global x global y global z global edges global G edges = list(G.edges) for relation in edges: if relation == (x,y) or relation == (x,z): G.remove_edge(*relation) #Bruteforce search lmao while run: for relation in edges: foundy=False foundz=False x = relation[0] for search in edges: if foundy: # print('x: {x}\nsearch[0]: {search[0]}') # exit() if search[0] == x: if search[1] != y: z = search[1] foundz = True else: if search[0] == x: y = search[1] foundy = True if foundy and foundz: clean() G.add_edge(x,z) G.add_edge(x,str(c)) G.add_edge(y,str(c)) G.add_edge(z,str(c)) edges = list(G.edges) c += 1 if c >= ITERATIONS: print(c) run = False # print(edges) fig, ax = plt.subplots() ax.set_facecolor('black') nx.draw(G, with_labels=False, node_shape='.',node_color='w', edge_color='w', node_size=20) ax.set_facecolor('black') ax.axis('off') fig.set_facecolor('black') # Shows graph plt.show() exit()
e2835ec928d7e08277cd651f190e20d23c444af2
[ "Python" ]
1
Python
MattWard97/wolframPy
0219a62f259c075f43ba5f95467ca8129ecf507f
531c510acfdbc89d12e16b4a5aeb8ae096da5375
refs/heads/master
<file_sep>#coding:utf-8 """ author @yuzt created on 2014.8.20 """ import traceback import threading import re import pymongo import time import requests try: import PyV8 from bs4 import BeautifulSoup except ImportError: print "Import Error" headers ={ "Host": "www.xici.net.co", "Connection": "keep-alive", "Cache-Control": "max-age=0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36", "Referer": "http://www.xici.net.co/nn/", "Accept-Encoding": "gzip, deflate, sdch", "Accept-Language": "en-US,en;q=0.8,zh-CN;q=0.6,zh;q=0.4,zh-TW;q=0.2", } threadLock = threading.Lock() ThreadNum = 50 def getIPs_proxy_ru(): IPs = [] proxy_types = ['gaoni','niming'] for proxy_type in proxy_types: proxy_url = 'http://proxy.com.ru/%s' % (proxy_type,) r = requests.get(proxy_url) soup = BeautifulSoup(r.content.decode('gbk')) html = str(soup) pattern = re.compile('共(\d+)页') total_page_num = int(pattern.findall(html)[0]) for i in range(min(20,total_page_num)): url = 'http://proxy.com.ru/%s/list_%s.html' % (proxy_type,i+1,) r = requests.get(url) soup = BeautifulSoup(r.content) table = soup.findAll('table')[7] trs = table.findAll('tr') for tr in trs[1:]: tds = tr.findAll('td') ip = tds[1].text.strip() port = tds[2].text.strip() IPs.append(ip+':'+port) return IPs def getIPs_proxy_digger(): with open('aes.js') as f: jsaes = f.read() with open('pad.js') as f: pad = f.read() socket_list = [] url = 'http://www.site-digger.com/html/articles/20110516/proxieslist.html' r = requests.get(url) soup = BeautifulSoup(r.content) definition = '' scripts = soup.find_all('script') for script in scripts: if 'baidu_union_id' in script.text: definition = script.text #print definition for tr in soup.find_all('tr'): if 'script' in str(tr): tds = tr.findAll('td') proxy_type = tds[1].text if proxy_type == 'Anonymous' :#and location == 'China': with PyV8.JSContext() as ctxt: ctxt.eval(jsaes) ctxt.eval(pad) ctxt.eval(definition) command = tds[0].script.text[15:-2] #print command socket_addres = ctxt.eval(command) socket_list.append(socket_addres) return socket_list def getIPs_kuaidaili(): ips = [] for i in range(10): url = 'http://www.kuaidaili.com/proxylist/%s/' % (i+1,) r = requests.get(url) soup = BeautifulSoup(r.content) tbody = soup.find('tbody') trs = tbody.find_all('tr') for tr in trs: tds = tr.find_all('td') ip = tds[0].text.strip() port = tds[1].text.strip() ips.append(ip+':'+port) return ips #- -use v8 engine to eval javascript code to get port def getIPs_org_pachong(): #glob = Global() socket_list = [] url = 'http://pachong.org/area/short/name/cn/type/high.html' r = requests.get(url) soup = BeautifulSoup(r.content) script = soup.findAll('script',attrs={'type':'text/javascript'})[2] js_code_part1 = script.text tbody = soup.find('tbody') trs = tbody.findAll('tr') for tr in trs: tds = tr.findAll('td') ip = tds[1].text js_code_part2 = tds[2].text with PyV8.JSIsolate(): with PyV8.JSContext() as ctxt: ctxt.eval(js_code_part1) port = ctxt.eval(js_code_part2[15:-2]) socket_address = '%s:%s' % (ip,port) proxy_type = tds[4].a.text if proxy_type == 'high': socket_list.append(socket_address) return socket_list def getIPs(): IPPool = [] getIPs_functions = [getIPs_proxy_digger, getIPs_proxy_ru, getIPs_kuaidaili, getIPs_org_pachong] for getIPs_function in getIPs_functions: try: ips = getIPs_function() print getIPs_function.__name__,len(ips) IPPool.extend(ips) except: print traceback.format_exc() IPPool = list(set(IPPool)) print "total IPs: " + str(len(IPPool)) return IPPool def verify_ip(socket_address): proxies = {"http":"http://" + socket_address} try: ip = socket_address.split(':')[0] verify_url1 = 'http://luckist.sinaapp.com/test_ip' verify_url2 = 'http://members.3322.org/dyndns/getip' r1 = requests.get(verify_url1,proxies=proxies,timeout=3) r2 = requests.get(verify_url2,proxies=proxies,timeout=3) return_ip1 = r1.content.strip() return_ip2 = r2.content.strip() if ip == return_ip1 and ip == return_ip2: # if ip == return_ip1: return True else: return False except: return False def worker(valid_ips,ip_list): for ip in ip_list: if verify_ip(ip) is True: threadLock.acquire() valid_ips.append(ip) threadLock.release() if __name__ == "__main__": client = pymongo.MongoClient('172.16.17.32') db = client['proxy_db'] proxy_collection = db['proxies'] while True: ips = getIPs() valid_ips = [] threads = [] for i in range(ThreadNum): ip_list = [ip for index,ip in enumerate(ips) if index%ThreadNum==i] t = threading.Thread(target=worker, args=(valid_ips,ip_list)) threads.append(t) for thread in threads: thread.start() for thread in threads: thread.join() print len(valid_ips) try: proxy_collection.drop() except Exception: pass for socket_address in valid_ips: ip,port = socket_address.split(':') print ip,port proxy_collection.insert({'ip':ip,'port':port}) time.sleep(1800) <file_sep>#!/usr/bin/env python # encoding: utf-8 from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" @app.route("/proxies") def get_proxies(): try: from pymongo import MongoClient client = MongoClient('192.168.3.11') db = client['proxy_db'] proxy_collection = db['proxies'] except: return 'error' html = '' for proxy in proxy_collection.find(): ip = proxy['ip'] port = proxy['port'] p = '<p>%s:%s</p>' % (ip,port) html += p return html if __name__ == "__main__": app.run(host='0.0.0.0') <file_sep>This is a simple program to get free http proxies.
23efc02b36f8b7046da1cdda18ca0f057305ff42
[ "Markdown", "Python" ]
3
Python
luckistmaomao/ZProxy
65ecfa68ebeebd3d5b9464bea14083c689e180fd
296960e1b716ce324b99d4d7fba3d6c0945635f6
refs/heads/master
<repo_name>xaiki/xkcd-1110<file_sep>/README.md XKCD #1110 ========== This could be a bit of a geeky dedication. * I loved [xkcd #1110](http://xkcd.com/1110/), and wanted to be able to explore it offline, * I wanted it to be quick and snappy * I wanted to play a bit with clutter, Gio and stuff… well, if you like it, use it, it's all WTFPL. Caching ------- if you put tiles in .cache (with the same name as the website), we'll use them.<file_sep>/hacks.py import sys import gi from gi.repository import Clutter from gi.repository import GdkPixbuf from gi.repository import Gio class PixbufTexture(Clutter.Texture): """ Represents a texture that loads its data from a pixbuf. """ __gtype_name__ = 'PixbufTexture' def __init__(self, uri=None): """ @type width: int @param width: The width to be used for the texture. @type height: int @param height: The height to be used for the texture. @type pixbuf: gdk.pixbuf @param pixbuf: A pixbuf from an other widget. """ super(PixbufTexture, self).__init__() def realize (self, width, height, pixbuf): self.set_width(width) self.set_height(height) # do we have an alpha value? if pixbuf.props.has_alpha: bpp = 4 else: bpp = 3 self.set_from_rgb_data( pixbuf.get_pixels(), pixbuf.props.has_alpha, pixbuf.props.width, pixbuf.props.height, pixbuf.props.rowstride, bpp, 0) return self @classmethod def new_from_uri (cls, uri, cb, args=None): inst = cls(uri) gfile = Gio.file_new_for_uri(uri) return gfile.load_contents_async(None, cls.receive_file, (inst, cb, args)) @classmethod def receive_file (cls, gfile, result, args): inst, cb, arg = args print "receive_file", args try: gfile.read_async (1, None, cls.read_complete, args) except Exception as exe: print exe return @classmethod def read_complete (cls, gfile, result, args): inst, cb, arg = args print "read_complete", args try: ins = gfile.read_finish (result) pixbuf = GdkPixbuf.Pixbuf.new_from_stream (ins, None) cb (inst.realize(pixbuf.get_width(), pixbuf.get_height(), pixbuf), arg) except gi._glib.GError as exe: print exe return if __name__ == '__main__': def add_to_stage (texture, stage): print "add_to_stage", texture, stage stage.add_actor(texture) if len(sys.argv) > 1: Clutter.init(None) stage = Clutter.Stage.get_default() PixbufTexture.new_from_uri (sys.argv[1], add_to_stage, stage) stage.set_size(500, 500) stage.set_color(Clutter.Color.new(0,255,0,0)) stage.show_all() stage.connect('destroy', Clutter.main_quit) Clutter.main() else: print "Provide the full path to the image to load" <file_sep>/xkcd.py #!/usr/bin/env python # -*- coding: utf-8 -*- import os import math import gi from gi.repository import GLib from gi.repository import Clutter from gi.repository import Gio from gi.repository import GdkPixbuf import hacks Clutter.init(None) # it'd be nice to have a better force model, but for now: FORCE = 50 # for some reason Clutter is lying to us… well… ACTOR_SIZE = 2048 smap = {'x':{-1:'e',1:'w'},'y':{1:'n',-1:'s'}} # if you set this, all magic goes away DEBUG=0 if DEBUG: sky_color = Clutter.Color.new(0,255,0,0) earth_color = Clutter.Color.new(255,0,0,0) debug_text = Clutter.Text() debug_text.set_text ("hello") debug_text.set_color (Clutter.Color.new(255,0,0,200)) else: sky_color = Clutter.Color.new(255,255,255,0) earth_color = Clutter.Color.new(0,0,0,0) class XaMap: def __init__(self, tex=None, stage=None): self.current_tile = [0, 0] self.cache_dir = os.path.abspath(".cache") self.base_url = "http://imgs.xkcd.com/clickdrag/" try: os.mkdir(self.cache_dir) except OSError: pass self.tile_cache = {} if (tex): self.tex = tex else: for i in range (-1, 2): for j in range (-1, 2): self.new_tile (i, j) # self.tex = ([self.new_col ( 1, 0, 0), # self.new_col ( 0, 0, 0), # self.new_col (-1, 0, 0)]) # self.tex = ([[None, self.new_tex (1, 0), None], # self.new_col (0, 0, 0), # [None, None, None]]) print "DEBUG", tex if (stage): self.stage = stage else: self.stage = Clutter.Stage.get_default() self.stage_size = self.stage.get_size() self.stage.set_background_color (sky_color) self.stage.set_title ("XKCD: #1110") self.scroll = Clutter.Group() self.scroll.set_size (-1, -1) self.stage.add_actor (self.scroll) self.stage.show() if DEBUG: self.stage.add_actor (debug_text) self.scroll.set_position (0, -1100) self.stage.connect ("key-press-event", self.on_key_press, self.scroll) def remove_tile (self, x, y): try: print "removing:", (x,y) self.scroll.remove_actor (self.tile_cache[x, y]) del(self.tile_cache[x, y]) except Exception as exe: print "Couldn't remove tile, probably never made it", exe def new_col (self, direction, x, y): self.new_tile (x + direction, y + 1) self.new_tile (x + direction, y) self.new_tile (x + direction, y - 1) self.remove_tile (x - 2*direction, y + 1) self.remove_tile (x - 2*direction, y) self.remove_tile (x - 2*direction, y - 1) def new_row (self, direction, x, y): self.new_tile (x + 1, y + direction) self.new_tile (x , y + direction) self.new_tile (x - 1, y + direction) self.remove_tile (x + 1, y - 2*direction) self.remove_tile (x , y - 2*direction) self.remove_tile (x - 1, y - 2*direction) def get_tile_filename (self, x, y): if (x<=0): x = x - 1 if (y>=0): y = y + 1 return "%d%c%d%c.png" % (abs(y), smap['y'][y/abs(y)], abs(x), smap['x'][x/abs(x)]) def new_tile (self, x, y, cb=None): if not cb: cb = self.show_tile f = self.get_tile_filename (x, y) uri = self.check_cache (f) print "loading tile for position: ", (x, y), "\tusing method", uri return hacks.PixbufTexture.new_from_uri (uri, cb, (x,y)) def check_cache (self, fn): try: os.stat (self.cache_dir + '/' + fn) except OSError: return ("http://imgs.xkcd.com/clickdrag/" + fn) return 'file://' + self.cache_dir + '/' + fn def set_current_tile (self, tile): self.current_tile = tile def show_tile (self, actor, pos): x, y = pos # nx = (-self.current_tile[0] + x)*ACTOR_SIZE # ny = (-self.current_tile[1] + y)*ACTOR_SIZE nx = -x*ACTOR_SIZE ny = -y*ACTOR_SIZE if self.tile_cache.has_key ((x,y)): print "Tile already cached at", (x,y), self.tile_cache raise KeyError self.tile_cache[(x,y)] = actor print "moving", actor, "to:", (x,y), self.current_tile, "to", nx, ny if not actor: print "No tile at", x, y return actor.set_position(nx, ny) self.scroll.add_actor (actor) action = Clutter.DragAction() # action.connect ("drag-begin", self.drag_begin_cb) action.connect ("drag-end" , self.drag_end_cb) action.connect ("drag-progress", self.drag_progress_cb, self.scroll) actor.add_action (action) actor.set_reactive (True) actor.props.clip_to_allocation = True def drag_begin_cb (self, action, actor, event_x, event_y, modifiers): print "DRAG START\t", self.scroll.get_position(), event_x, event_y def drag_end_cb (self, action, actor, event_x, event_y, modifiers): self.recenter () def drag_progress_cb (self, action, actor, delta_x, delta_y, arg=None): if arg: arg.move_by (delta_x, delta_y) return False def do_recenter (self, tile, motion): print "recentering", tile, motion self.set_current_tile(tile) if DEBUG: debug_text.set_text ("current Tile:" + str(tile) + self.get_tile_filename(*tile)) if motion[0]: print "adding a col" self.new_col(motion[0], *tile) if motion[1]: print "adding a row" self.new_row(motion[1], *tile) def on_key_press (self, stage, event, actor): if event.keyval == Clutter.KEY_q: Clutter.main_quit() if event.keyval == Clutter.KEY_Up: actor.move_by (0, FORCE) if event.keyval == Clutter.KEY_Down: actor.move_by (0, -FORCE) if event.keyval == Clutter.KEY_Left: actor.move_by (FORCE, 0) if event.keyval == Clutter.KEY_Right: actor.move_by (-FORCE, 0) self.recenter () def recenter (self): pos = self.scroll.get_position() tile = [1 + int(math.floor((pos[i] - self.stage_size[i])/ACTOR_SIZE)) for i in range(2)] if (pos[1] > 0): self.stage.set_background_color (sky_color) else: self.stage.set_background_color (earth_color) print "recenter?", pos, tile, self.current_tile if (tile != self.current_tile): motion = [tile[i] - self.current_tile[i] for i in range(2)] self.do_recenter (tile, motion) def show_cb (actor, coord): x, y = coord # print "show:", coord tex = XaMap() Clutter.main()
81e8de94124dd136aff3eebe971b23e5f8ac39c7
[ "Markdown", "Python" ]
3
Markdown
xaiki/xkcd-1110
846f6657eed08198a7049f69fff1b7e85f6a1a5e
20c077a6fb71c5088e8a75a358d57132e190b81b
refs/heads/master
<repo_name>rhosak/tomo-tsp<file_sep>/adj_gen.py #!/usr/bin/env python3 """adj_gen.py Generate TSP adjacency matrix for polarization tomography. 2018 <NAME> <<EMAIL>> Quantum Optics Lab Olomouc""" from copy import deepcopy import numpy as np ################################## # Wave plate angle specification # ################################## # The wave plate angles are stored in the ANGLES variable. # The code below shows wave plate angle specification # for a six-projection scheme (H, V, D, A, R, L), # with a half-wave plate (HWP) and a quarter-wave plate (QWP). ANGLES = np.array([[0, 0], [45, 0], [22.5, 0], [-22.5, 0], [0, 45], [0, -45]]) # For a three-bases scheme (H/V, D/A, R/L), # the ANGLES variable would look like this: # ANGLES = np.array([[0, 0], # [22.5, 0], # [0, 45]]) <file_sep>/README.md # tomo-tsp Optimizing the order of polarization projections for n-qubit state tomography. This repository provides supplementary material to the following paper by <NAME>, <NAME>, and <NAME>: **The optimal strategy for photonic quantum tomography**, [Opt. Express 26, 32878 (2018)](https://doi.org/10.1364/OE.26.032878), preprint: [arXiv 1809.07521 [quant-ph]](https://arxiv.org/abs/1809.07521). ## Polarization tomography and the traveling salesman problem TSP See [TOMO_TSP.md](TOMO_TSP.md) for the basic information on polarization tomography and its specification as TSP. ## Software prerequisities * [Python 3](https://www.python.org/) * Python 3 modules: * [NumPy](http://www.numpy.org/) * [Matplotlib](https://matplotlib.org/) (optional, for plotting) * [Concorde](http://www.math.uwaterloo.ca/tsp/concorde/downloads/downloads.htm) TSP solver ## The workflow See [the wave_plate_tsp.ipynb Jupyter notebook](wave_plate_tsp.ipynb) for a detailed guide on how to formulate and solve the TSP. The notebook solves the tomography TSP for polarization-encoded photonic qubits, asuuming one single-photon detector per qubit (the _six-state scheme_). ## TSP solutions The TSP solutions for n-qubit (n up to five) polarization tomography, generated by Concorde, are stored in the files `nq_6s.sol`, with `n` being a number from 1 to 5. The files contain a list of indices that dictate the TSP-optimized order of the polarization projections. For the one-qubit case, the projections `H`, `V`, `D`, `A`, `R`, `L` correspond to indices 0, 1, 2, 3, 4, 5, 6, respectively. For higher-qubit cases, the order of the indices follows this logic: `HHH`, `HHV`, ..., `HHL`, `HVH`, `HVV`, ..., `HVL`, ..., `HLL`, `VHH`, `VHV`, ..., `VHL`, ..., `LLL`. <file_sep>/TOMO_TSP.md # Polarization-encoded qubit tomography basics Tomography of a polarization-encoded qubit consists of polarization projection measurements. These are often the following: * H: horizontal polarization * V: vertical polarization * D: diagonal polarization * A: anti-diagonal polarization * R: right-circular polarization * L: left-circular polarization The experimental scheme for the measurement of these projections can look like this: ![polarization projection measurement scheme](images/tomo_scheme_6s.png) This scheme consists of the following: * HWP: a half-wave plate * QWP: a quarter-wave plate * PBS: a polarizing beamsplitter * SPD: a single-photon detector Different projections can be measured by adjusting the angles of the HWP and QWP according to this table: | projection | HWP angle | QWP angle | |------------|-----------|-----------| | H | 0.0 | 0 | | V | 45.0 | 0 | | D | 22.5 | 0 | | A | -22.5 | 0 | | R | 0.0 | 45 | | L | 0.0 | -45 | The measurement duration can be shortened if the order of projection measurement is optimized, so that the least angle is traveled by the waveplates during all the necessary transition between projections. This is desirable especially for systems consisting of n qubits, as the number of measurements scales as 6^n. # Travelling salesman problem (TSP) formulation of tomography The one-qubit tomography can be represented using this graph: ![A graph representation of one-qubit tomography. Six nodes represent the projection measurements](images/tomo_graph.png) The six nodes of the graph represent the six projection measurements. The edges (lines) between the nodes are weighted. The weight is the maximal angle (absolute-valued) traveled by any of the two waveplates during a transision between the two measurements. The graph weights can be represented by the adjacency matrix, shown below: ![The adjacency matrix for one-qubit tomography](images/adj1.png) The values of the matrix elements can be checked using the waveplate angle table above.
78a24b4066723d3a21cf5ea8cdb2120e9e4213d3
[ "Markdown", "Python" ]
3
Python
rhosak/tomo-tsp
71b6a94f7041787b0a216d751c63db7ea8b6bc3e
ae004e3a3af537180e37b5d92e1069bc71cb8a0b
refs/heads/master
<repo_name>codeyu/SQLServer-Toolbox<file_sep>/Scripts/查询前10名性能最差的查询语句.sql SELECT TOP 10 TEXT AS 'SQL Statement' ,last_execution_time AS 'Last Execution Time' ,(total_logical_reads + total_physical_reads + total_logical_writes) / execution_count AS [Average IO] ,(total_worker_time / execution_count) / 1000000.0 AS [Average CPU Time (sec)] ,(total_elapsed_time / execution_count) / 1000000.0 AS [Average Elapsed Time (sec)] ,execution_count AS "Execution Count" ,qp.query_plan AS "Query Plan" FROM sys.dm_exec_query_stats qs CROSS APPLY sys.dm_exec_sql_text(qs.plan_handle) st CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp ORDER BY total_elapsed_time / execution_count DESC<file_sep>/Scripts/常用数据库管理脚本.sql --1.查看数据库的版本 select @@version as Version --2.查看数据库所在机器操作系统参数 exec master..xp_msver --3.查看数据库启动的参数 exec sp_configure --4.查看数据库启动时间 select convert(varchar(30),login_time,120) as StartRunTime from master..sysprocesses where spid=1 --5.查看数据库服务器名和实例名 print 'Server Name...............:' + convert(varchar(30),@@SERVERNAME) print 'Instance..................:' + convert(varchar(30),@@SERVICENAME) --6. 查看所有数据库名称及大小 exec sp_helpdb --重命名数据库用的SQL sp_renamedb 'old_dbname', 'new_dbname' --7. 查看所有数据库用户登录信息 sp_helplogins --8.查看所有数据库用户所属的角色信息 sp_helpsrvrolemember --修复迁移服务器时孤立用户时,可以用的fix_orphan_user脚本或者LoneUser过程 --9.更改某个数据对象的用户属主 sp_changeobjectowner [@objectname =] 'object', [@newowner =] 'owner' --注意:更改对象名的任一部分都可能破坏脚本和存储过程。 --把一台服务器上的数据库用户登录信息备份出来可以用add_login_to_aserver脚本 --10.查看某数据库下,对象级用户权限 sp_helprotect --11. 查看链接服务器 sp_helplinkedsrvlogin --12.查看远端数据库用户登录信息 sp_helpremotelogin --13.查看某数据库下某个数据对象的大小。还可以用sp_toptables过程看最大的N(默认为50)个表 sp_spaceused @objname --14.查看某数据库下某个数据对象的索引信息 sp_helpindex @objname --15.还可以用SP_NChelpindex过程查看更详细的索引情况 SP_NChelpindex @objname --clustered索引是把记录按物理顺序排列的,索引占的空间比较少。 --对键值DML操作十分频繁的表我建议用非clustered索引和约束,fillfactor参数都用默认值。 --16.查看某数据库下某个数据对象的的约束信息 sp_helpconstraint @objname --17.查看数据库里所有的存储过程和函数 use @database_name sp_stored_procedures --18.查看存储过程和函数的源代码 sp_helptext [url=mailto:'@procedure_name']'@procedure_name'[/url] --查看包含某个字符串@str的数据对象名称 select distinct object_name(id) from syscomments where text like [url=mailto:'%@str%']'%@str%'[/url] --创建加密的存储过程或函数在AS前面加WITH ENCRYPTION参数 --解密加密过的存储过程和函数可以用sp_decrypt过程 --19.查看数据库里用户和进程的信息 sp_who --查看SQL Server数据库里的活动用户和进程的信息 sp_who 'active' --查看SQL Server数据库里的锁的情况 sp_lock --进程号1--50是SQL Server系统内部用的,进程号大于50的才是用户的连接进程. --spid是进程编号,dbid是数据库编号,objid是数据对象编号 --查看进程正在执行的SQL语句 select * from master..sysprocesses dbcc inputbuffer(spid) --推荐大家用经过改进后的sp_who3过程可以直接看到进程运行的SQL语句 http://www.sqlservercentral.com/scripts/sp_who3/69906/ --11.查看和收缩数据库文章文件的方法 --查看所有数据库文章文件大小 dbcc sqlperf(logspace) --如果某些文章文件较大,收缩简单恢复模式数据库文章,收缩后@database_name_log的大小单位为M backup log @database_name with no_log dbcc shrinkfile (@database_name_log, 5) --13.查看数据库在哪里 SELECT * FROM sysfiles<file_sep>/Scripts/查看阻塞.sql SELECT SPID = er.session_id ,STATUS = ses.STATUS ,[LOGIN] = ses.login_name ,HOST = ses.host_name ,BlkBy = er.blocking_session_id ,DBName = DB_NAME(er.database_id) ,CommandType = er.command ,SQLStatement = st.text ,BlockingText = bst.text ,ObjectName = OBJECT_NAME(st.objectid) ,ElapsedMS = er.total_elapsed_time ,CPUTime = er.cpu_time ,IOReads = er.logical_reads + er.reads ,IOWrites = er.writes ,LastWaitType = er.last_wait_type ,StartTime = er.start_time ,Protocol = con.net_transport ,ConnectionWrites = con.num_writes ,ConnectionReads = con.num_reads ,ClientAddress = con.client_net_address ,Authentication = con.auth_scheme FROM sys.dm_exec_requests er OUTER APPLY sys.dm_exec_sql_text(er.sql_handle) st LEFT JOIN sys.dm_exec_sessions ses ON ses.session_id = er.session_id LEFT JOIN sys.dm_exec_connections con ON con.session_id = ses.session_id LEFT JOIN sys.dm_exec_requests ber ON er.blocking_session_id=ber.session_id OUTER APPLY sys.dm_exec_sql_text(ber.sql_handle) bst WHERE er.session_id > 50 ORDER BY er.blocking_session_id DESC,er.session_id<file_sep>/Scripts/找出哪些表的Index 需要改进.sql SELECT user_seeks * avg_total_user_cost * (avg_user_impact * 0.01) AS [index_advantage] ,migs.last_user_seek ,mid.[statement] AS [Database.Schema.Table] ,mid.equality_columns ,mid.inequality_columns ,mid.included_columns ,migs.unique_compiles ,migs.user_seeks ,migs.avg_total_user_cost ,migs.avg_user_impact FROM sys.dm_db_missing_index_group_stats AS migs WITH (NOLOCK) INNER JOIN sys.dm_db_missing_index_groups AS mig WITH (NOLOCK) ON migs.group_handle = mig.index_group_handle INNER JOIN sys.dm_db_missing_index_details AS mid WITH (NOLOCK) ON mig.index_handle = mid.index_handle ORDER BY index_advantage desc<file_sep>/Scripts/生成表结构脚本.sql use DBName; SELECT 表名 = case when a.colorder=1 then d.name else '' end, 表说明 = case when a.colorder=1 then isnull(f.value,'') else '' end, 字段名称 = a.name, 类型 = b.name, 长度 = COLUMNPROPERTY(a.id,a.name,'PRECISION'), 主键 = case when exists(SELECT 1 FROM sysobjects where xtype='PK' and name in( SELECT name FROM sysindexes WHERE indid in( SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid ))) then '√' else '' end, 默认值=isnull(e.text,''), 允许空=case when a.isnullable=1 then '√'else '' end, 字段说明 = isnull(g.[value],'') FROM syscolumns a left join systypes b on a.xtype=b.xusertype inner join sysobjects d on a.id=d.id and d.xtype='U' and d.name<>'dtproperties' left join syscomments e on a.cdefault=e.id left join sys.extended_properties g on a.id=g.major_id and a.colid=g.minor_id left join sys.extended_properties f on d.id=f.major_id and f.minor_id =0 where d.name='TableName' --如果只查询指定表,加上此条件 order by a.id,a.colorder <file_sep>/README.md # SQLServer-Toolbox
eedd6da33bd0d18de64a8e0673219223377cfa3d
[ "Markdown", "SQL" ]
6
SQL
codeyu/SQLServer-Toolbox
39a9031c2d555b548c27b655ff06af75468abc55
88f130be21829052d75348b528a9e2ab04c595ff
refs/heads/master
<repo_name>LucasBeeman/Classes<file_sep>/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Classes { public class myCharacter { public string name; public int health; public int mana; public int armor; public int level; public string playerClass; } class Program { static void Main(string[] args) { string[] myClasses = playerClasses(); myCharacter mage = new myCharacter(); mage.name = "Joe"; mage.health = 100; mage.mana = 100; mage.armor = 25; mage.level = 1; mage.playerClass = myClasses[0]; Console.WriteLine($"Name : {mage.name}\nHealth: {mage.health}\nMana: {mage.mana}\nArmor: {mage.armor}\nLevel: {mage.level}\nClass: {mage.playerClass}"); Console.WriteLine($"\n\"Do you know {mage.name}?\"\n\"Whoes {mage.name}?\"\n\"{mage.name}mama!\""); Console.ReadKey(); } public static string[] playerClasses() { string[] myClasses = { "mage", "barbarian", "wizard" }; return myClasses; } } }
f62e728ec33cd1e94a14e9906739ba2757e8a105
[ "C#" ]
1
C#
LucasBeeman/Classes
3b74ab6dbbae3d3481711b811109bc07c1e82322
af81af79ab7763b55204cd6a25806dc80d2ef26d
refs/heads/master
<repo_name>vdbg/cli-example-nodejs<file_sep>/get_rssi.sh device="$1" btconnected=0 btcurrent=-1 counter=0 notconnected="0" connected="1" rssi=-1 #Command loop: while [ 1 ]; do cmdout=$(hcitool rssi $device) btcurrent=$(echo $cmdout | grep -c "RSSI return value") 2> /dev/null rssi=$(echo $cmdout | sed -e 's/RSSI return value: //g') if [ $btcurrent = $notconnected ]; then echo "Attempting connection..." rfcomm connect 0 $device 1 2> /dev/null >/dev/null & sleep 1 fi if [ $btcurrent = $connected ]; then echo "Device connected. RSSI: "$rssi fi if [ $btconnected -ne $btcurrent ]; then if [ $btcurrent -eq 0 ]; then echo "GONE!" fi if [ $btcurrent -eq 1 ]; then echo "HERE!" fi btconnected=$btcurrent fi sleep 1 done <file_sep>/BT.md Notifies SmartThings switch devices when a given Bluetooth device is in range # Prequisites `sudo apt-get install nodejs npm` # Identify devices - `sudo bluetoothctl` - `scan on`: to see devices. Note the address of the device of interest - Optional: for RSSI option (seeing device's strength, a proxy for distance): - `advertise on`: so that devices can see you - `pair MAC_ADDRESS`: for each device to pair. Alternative is to initiate pairing from target device Note: may have to answer code or answer prompts on one or both of devices - `advertise off` and `scan off` when done - `quit` # Running script - Edit `bt.config` to add the SmartThings token. - Create one "Simulated Switch Device" per Bluetooth device on https://account.smartthings.com - Add one entry in `bt.config` for each one of the Bluetooth devices with the device Bluetooth mac address and the device uuid from SmartThings - Run `sudo ./bt.sh` to test <file_sep>/auto_off.sh #!/bin/bash config_file="bt.config" [ -f "$config_file" ] || { echo "$config_file file not found."; exit 1; } . "$config_file" [ -n "$SMARTTHINGS_CLI_TOKEN" ] || { echo "SMARTTHINGS_CLI_TOKEN is not set."; exit 1; } export SMARTTHINGS_CLI_TOKEN [ -n "$ST_DEVICE_ID" ] || { echo "ST_DEVICE_ID is not set."; exit 1; } get_st_status () { ST_STATUS=unknown ST_STATUS=$(sthelper statusvaluebyid $1) echo "$2status is: $ST_STATUS" } get_st_status $ST_DEVICE_ID "Computer " if [ "$ST_STATUS" = "off" ]; then echo "Shutting down computer!" shutdown now else if [ -n "$PROCESSES_TO_KILL" ] && [ -n "$ST_KILLPROCS_ID" ]; then get_st_status $ST_KILLPROCS_ID "Processes " if [ "$ST_STATUS" = "off" ]; then echo "Killing: $PROCESSES_TO_KILL" for process in "$PROCESSES_TO_KILL"; do killall $process done fi fi fi <file_sep>/bt.sh #!/bin/bash declare -A devices declare -A deviceStatuses config_file="bt.config" stop_file="bt.stop" bt_retry=false [ -f "$config_file" ] || { echo "$config_file file not found."; exit 1; } . "$config_file" [[ ${#devices[@]} -gt 0 ]] || { echo "No devices defined."; exit 1; } [ -n "$SMARTTHINGS_CLI_TOKEN" ] || { echo "SMARTTHINGS_CLI_TOKEN is not set."; exit 1; } export SMARTTHINGS_CLI_TOKEN probe_one_other_method () { cmdout=$(hcitool cc $mac_of_device \ && hcitool auth $mac_of_device \ && hcitool rssi $mac_of_device \ && hcitool dc $mac_of_device ) echo "$name_of_device: Output: $cmdout" btcurrent=-1 btcurrent=$(echo $cmdout | grep -c "RSSI return value") 2> /dev/null rssi=$(echo $cmdout | sed -e 's/RSSI return value: //g') if [ $btcurrent = 1 ]; then echo "$name_of_device: Device connected with RSSI: $rssi" btcurrent="turnonbyid" else echo "$name_of_device: Device not connected!" btcurrent="turnoffbyid" fi } probe_one () { cmdout=$(l2ping -c 1 $mac_of_device) echo "$name_of_device: Output: $cmdout" btcurrent=-1 btcurrent=$(echo $cmdout | grep -c "1 received") 2> /dev/null if [ $btcurrent = 1 ]; then echo "$name_of_device: Device connected" btcurrent="turnonbyid" else echo "$name_of_device: Device not connected!" btcurrent="turnoffbyid" fi } probe_bt () { declare uuid_of_device=$3 declare mac_of_device=$2 declare name_of_device=$1 echo "$name_of_device: Probing device with mac $mac_of_device and uuid $uuid_of_device ..." probe_one if [ "${deviceStatuses[$uuid_of_device]}" != "$btcurrent" ]; then echo "$name_of_device: Status changed to $btcurrent" btold=$btcurrent if [ "$bt_retry" = "true" ]; then echo "Retry enabled; calling again to be sure" btcurrent=-1 sleep 30s probe_one fi if [ "$btold" = "$btcurrent" ]; then echo "$name_of_device: Updating status to $btcurrent ..." sthelper $btcurrent $uuid_of_device if [ $? = 0 ]; then deviceStatuses[$uuid_of_device]=$btcurrent fi else echo "$name_of_device: status change not confirmed; changed to $btcurrent" fi fi } probe_bts() { echo "Probing devices: $@" for device in "$@"; do probe_bt "$device" ${devices[$device]} done } while : do if [ $# -eq 0 ]; then echo "Probing all devices" probe_bts "${!devices[@]}" else echo "Probing selected devices" probe_bts "$@" fi [ -f "$stop_file" ] && { echo "$stop_file found; exiting."; exit 0; } sleep 5m [ -f "$stop_file" ] && { echo "$stop_file found; exiting."; exit 0; } done
aacebe7f584e1b408596d56f9cc6ed13c77496b9
[ "Markdown", "Shell" ]
4
Shell
vdbg/cli-example-nodejs
270290a5a513aeaa4fa831e21e70c4351fbc6ca0
816499b9371b09db22b8ea1f960b0d2fd430a0ab
refs/heads/master
<file_sep># Laravel5 ### 先将.env文件的数据库信息改为自己的 ### 在新建一个名为laravel5的数据库,并将laravel5.sql导入到laravel5数据库中 <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Article extends Model { // public function index() { return view('admin/article/index')->withArticles(Article::all()); } public function hasManyComments() { return $this->hasMany('App\Comment', 'article_id', 'id'); } }
efa70c9a2473d6e4166f859143217cbb0558300e
[ "Markdown", "PHP" ]
2
Markdown
whyIsHt/laravel5-blog
4f45c0892e5db2e2486a9e33b14041bb274f514d
35882f52f76e7fc79190fadf0f4e5ed68d7005a3
refs/heads/master
<file_sep>data <- read.csv("household_power_consumption.txt", sep=";", na.strings="?") subset <- subset(data, Date == "1/2/2007" | Date == "2/2/2007") subset[, "Date"] <- as.Date(strptime(subset[, "Date"], format='%d/%m/%Y')) png(filename="plot1.png") hist(subset[,"Global_active_power"], col="red", main="Global Active Power", xlab="Global Active Power (kilowatts)" ) dev.off() <file_sep>data <- read.csv("household_power_consumption.txt", sep=";", na.strings="?") subset <- subset(data, Date == "1/2/2007" | Date == "2/2/2007") xline <- strptime(paste(subset$Date, subset$Time), format="%d/%m/%Y %H:%M:%S") png(filename="plot3.png") plot(x=xline, y=subset[,"Sub_metering_1"], type="l",ylab="Energy sub metering", main="", xlab="") lines(x=xline, y=subset[,"Sub_metering_2"], col="red") lines(x=xline, y=subset[,"Sub_metering_3"], col="blue") legend("topright", lty=1, col = c("black", "blue", "red"), legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3")) dev.off() <file_sep>data <- read.csv("household_power_consumption.txt", sep=";", na.strings="?") subset <- subset(data, Date == "1/2/2007" | Date == "2/2/2007") xline <- strptime(paste(subset$Date, subset$Time), format="%d/%m/%Y %H:%M:%S") png(filename="plot4.png") par(mfrow = c(2, 2)) plot(x=xline, y=subset[,"Global_active_power"], type="l",ylab="Global Active Power", main="", xlab="") plot(x=xline, y=subset[,"Voltage"], type="l",ylab="Voltage", main="", xlab="datetime") plot(x=xline, y=subset[,"Sub_metering_1"], type="l",ylab="Energy sub metering", main="", xlab="") lines(x=xline, y=subset[,"Sub_metering_2"], col="red") lines(x=xline, y=subset[,"Sub_metering_3"], col="blue") legend("topright", lty=1, col = c("black", "blue", "red"), legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), bty = "n") plot(x=xline, y=subset[,"Global_reactive_power"], type="l",ylab="Global_reactive_power", main="", xlab="datetime") dev.off()
4cf771f2ce0606fd53f3440f09f1e7042847aa96
[ "R" ]
3
R
typemiguel/ExData_Plotting1
a6d5c9922eecafdbb92ba37d4a65a244baeeeb8a
2d395edbf8245b9b6434ff0900e3f103df1d4ccb
refs/heads/master
<repo_name>mahuan2372/nxy<file_sep>/src/view/page/tableAdmin/validate.js let checkAge = (rule, value, callback) => { if (value === '') { return callback(new Error('必填项')); } if (value == '0') { return callback(new Error('不能为0')); } if (value == -1) { return callback(); } let rez = /^\d*(\.\d{1,2})?$/; if (!rez.test(value)) { return callback(new Error('正数,小数点后两位')); } if (value > 9999999) { return callback(new Error('最大不能超过9999999')); } return callback(); }; let laayt = (rule, value, callback) => { if (value === '') { return callback(new Error('必填项')); } let rez = /^\d+(\.\d{1,2})?$/; if (!rez.test(value)) { return callback(new Error('正数,小数点后两位')); } return callback(); }; let checkAge_ = (rule, value, callback) => { if (value === '') { return callback(new Error('必填项')); } let rez = /^\d+(\.\d{1,2})?$/; if (!rez.test(value)) { return callback(new Error('正数,小数点后两位')); } if (value > 100) { return callback(new Error('最大不能超过100')); } return callback(); }; let checkAge__ = (rule, value, callback) => { if (value === '') { return callback(new Error('必填项')); } if (value == -1) { return callback(); } let rez = /^\d+$/; if (!rez.test(value)) { return callback(new Error('正整数')); } if (value > 9999999) { return callback(new Error('最大不能超过9999999')); } return callback(); }; let perday_ = (rule, value, callback) => { if (value === '') { return callback(new Error('必填项')); } if (value == -1) { return callback(); } let rez = /^[0-9]*$/; if (!rez.test(value)) { return callback(new Error('交易笔数格式错误')); } return callback(); }; let moblieValidate = (rule, value, callback) => { if (value === '') { return callback(new Error('必填项')); } let rez = /^[1][0-9]{10}$/; if (!rez.test(value)) { return callback(new Error('手机格式失败')); } return callback(); } let cardValidate = (rule, value, callback) => { if (value == '') { return callback(new Error('必填项')); } let rez = /(^\d{10,25}$)/; if (!rez.test(value)) { return callback(new Error('数字值,长度10-25之间')); } return callback(); } let idcardValidate = (rule, value, callback) => { if (value == '') { return callback(new Error('必填项')); } let rez = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; if (!rez.test(value)) { return callback(new Error('身份证格式错误')); } return callback(); } let nubg = (rule, value, callback) => { if (value == '') { return callback(); } if (value > 500) { return callback(new Error('一次生成小于500个')); } return callback(); } let nubgnade = { validator: nubg, trigger: 'change' } let cardNo = { validator: cardValidate, trigger: 'change' } let laayttui={ validator:laayt, trigger: 'change' } let idcard = { validator: idcardValidate, trigger: 'change' } let mob = { validator: moblieValidate, trigger: 'change' } let req = { required: true, message: "必填项", trigger: "change" }; let numb = { type: 'number', message: '必须为数字' }; let numVali = { validator: checkAge, trigger: 'blur' }; let numVali_ = { validator: checkAge_, trigger: 'change' }; let numVali__ = { validator: checkAge__, trigger: 'change' }; let Maximum = { validator: perday_, trigger: 'change' }; let wx = { stlCycle: [req], feeRate: [numVali_], maxTxnAmt: [numVali], daySumCnt: [Maximum], time: [req] }; let zfb = { stlCycle_: [req], feeRate_: [numVali_], maxTxnAmt_: [numVali], daySumCnt_: [Maximum], time_: [req] }; let zfb1 = { stlCycle1: [req], feeRate1: [numVali_], maxTxnAmt1: [numVali], daySumCnt1: [numVali__], time_: [req] }; let yinlian = { thjjkfl: [req, numVali_], thjjksx: [req, numVali], thjjkxx: [req, numVali], thdjkfl: [req, numVali_], thdjksx: [req, numVali], thdjkxx: [req, numVali], } export let jiben = { rtime: [req], mchntName: [req], mchntType: [req], legalPerson: [req], license: [req], mcc: [req], businessDescOne: [req], businessDescTwo: [req], businessDesc: [req], nature: [req], simpMchntName: [req], contacts: [req], legalPersonId: [req, idcard], registeredCapital: [req,laayttui], registAddress: [req], contPhone: [req, mob], contAddr: [req], contaddr: [req], provCd: [req], cityCd: [req], countyCd: [req], busiAddress: [req], certMeet: [req], cardCorrect: [req], certCorrect: [req], certOpposite: [req] } export let jiesuan = { cardType: [req], realName: [req], certNo: [req, idcard], cardNo: [cardNo], } let base = { ...jiben, //结算 ...jiesuan, //以上为商户信息 ...yinlian //以上是银行二维码 }; export let allValidata = { ...wx, ...zfb1, ...base } export let wxValidata = { ...wx, ...base } export let zfbValidata = { ...zfb1, ...base } export let zfValidata = { ...zfb, ...wx, ...yinlian, ...jiesuan } export let jigou = { orgId: [{ required: true, message: "无所选支行", trigger: "change" }], payMd: [req], stlCycle: [req], feeRateStr: [req,numVali_], minRateStr: [req,numVali_], maxTxnAmtStr: [req,numVali], daySumCnt: [req,Maximum], compMaxTxnAmtStr: [req,numVali], time:[req], number:[req,nubgnade] };<file_sep>/src/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' import './assets/css/base.css' import axios from './httpjs.js' import store from './store/index.js' import viewComponent from './view.js' import exportFile from "./components/exportFile"; import state from './components/common/state'; import mqtt from './components/common/mqtt.js'; import dialogTree from './components/dialogTree'; import { formatDate } from './components/common/date' Vue.config.productionTip = false; Vue.use(ElementUI); Vue.filter('formatDate', function (value, option) { if (!value) { return '' } var date = new Date(value); return formatDate(date, option); }) Vue.component('exportFile', exportFile); Vue.component('dialogTree', dialogTree); for (let i in viewComponent) { Vue.component(i, viewComponent[i]) } Vue.prototype.$http = axios; Vue.prototype.Select = state('selectData'); Vue.prototype.mqtt = mqtt() Vue.mixin({ created: function () { this.btnList = {}; if (this.app) { for (let i = 0; i < this.app.length; i++) { this.btnList[this.app[i].menuId] = this.app[i].menuNm; } }; }, props: ['app'] }) /* eslint-disable no-new */ window.vm = new Vue({ el: '#app', router, store, components: { App }, template: '<App/>', mounted() {} }); /*自定义菜单*/ // let List = [{ // iconName: "zhuowei", // menuNm: "商户管理", // children: [{ // menuUrl: "tableCardList", // iconName: "zhuowei", // menuNm: "商户管理" // }, // { // menuUrl: "merChantAuthList", // iconName: "shenhe", // menuNm: "商户审核" // }, // { // menuUrl: "qrcodeList", // iconName: "shoukuan", // menuNm: "收款码管理" // }, // { // menuUrl: "toMerchantRateMgr", // iconName: "feilv", // menuNm: "商户费率" // }, // { // menuUrl: "archiveList", // iconName: "zhuxiao", // menuNm: "商户注销管理" // }, // ] // }, // { // iconName: "jiaoyi", // menuNm: "交易管理", // children: [{ // menuUrl: "order", // iconName: "jiaoyi", // menuNm: "交易管理" // }, ] // }, // { // iconName: "baobiao", // menuNm: "报表汇总", // children: [{ // menuUrl: "merchantDay", // iconName: "shanghu", // menuNm: "商户汇总" // }, // { // menuUrl: "orderDay", // iconName: "jiaoyi", // menuNm: "交易汇总" // }, // ] // }, // { // iconName: "shebei", // menuNm: "设备管理", // children: [{ // menuUrl: "invalid", // iconName: "dayinji", // menuNm: "打印机管理" // }, // { // menuUrl: "continental", // iconName: "dongtai", // menuNm: "动态码牌管理" // }, // { // menuUrl: "management", // iconName: "sim", // menuNm: "sim卡管理" // }, // ] // }, // { // iconName: "xitong", // menuNm: "系统管理", // children: [{ // menuUrl: "mgrUser", // iconName: "zhanghu", // menuNm: "账户管理" // }, // { // menuUrl: "mgrRole", // iconName: "juese", // menuNm: "角色管理" // }, // { // menuUrl: "platOrg", // iconName: "zhihang", // menuNm: "支行管理" // }, // { // menuUrl: "orgExtCfg", // iconName: "zhfeilv", // menuNm: "支行费率管理" // }, // ] // }, // ]; // localStorage.setItem("menu", JSON.stringify(List)); <file_sep>/src/base.js let baseurl="http://192.168.1.247:8080/buybal-entrances-zuul"; // baseurl="http://192.168.1.184:7070/buybal-entrances-zuul"; // baseurl='http://192.168.1.8:3000/mock/32'; // baseurl='http://192.168.1.184:6060/buybal-entrances-zuul'; export {baseurl} <file_sep>/README.md "# nxy" <file_sep>/src/components/common/state.js export default function (name) { var state = {}; return { get(name) { let arr = name.split('.'), active; for (let i = 0, len = arr.length; i < len; i++) { if (state[arr[i]]) { active = state[arr[i]]; } else { return null } } return active; }, set(name, data) { state[name] = data; } } } <file_sep>/src/view.js import tableCardList from './view/page/tableAdmin/tableAdmin.vue' //商户管理 import merChantAuthList from './view/page/merChantAuthList/merChantAuthList.vue' //商户审核 import qrcodeList from './view/page/qrcodeList/qrcodeList.vue' //收款码管理 import editPw from './view/page/editPw/editPw.vue' //修改密码 import toMerchantRateMgr from './view/page/toMerchantRateMgr/toMerchantRateMgr.vue' //商户费率 import archiveList from './view/page/archiveList/archiveList.vue' //商户注销管理 import order from './view/page/order/order.vue' //交易管理 import merchantDay from './view/page/merchantDay/merchantDay.vue' //商户汇总 import orderDay from './view/page/orderDay/orderDay.vue' // 交易汇总 import mgrUser from './view/page/mgrUser/mgrUser.vue' // 账户管理 import mgrRole from './view/page/mgrRole/mgrRole.vue' // 角色管理 import platOrg from './view/page/platOrg/platOrg.vue' // 支行管理 import orgExtCfg from './view/page/orgExtCfg/orgExtCfg.vue' // 支行费率管理 import invalid from './view/page/invalid/invalid.vue' // 打印机管理 import continental from './view/page/continental/continental.vue' // 动态码牌管理 import management from './view/page/management/management.vue' // sim管理 export default { 'c100000100':tableCardList, 'ceditPw':editPw, 'c100000200':merChantAuthList, 'c100000300':qrcodeList, 'c100000400':toMerchantRateMgr, 'c100000500':archiveList, 'c200000100':order, 'c700000601':merchantDay, 'c700000602':orderDay, 'c700000100':mgrUser, 'c700000200':mgrRole, 'c700000300':platOrg, 'c700000400':orgExtCfg, 'c600000100':invalid, 'c600000200':continental, 'c600000300':management }<file_sep>/src/view/page/platOrg/validate.js const req = { required: true, trigger: "change", message: '不能为空' }; let moblieValidate = (rule, value, callback) => { let rez = /^[1][0-9]{10}$/; if (!rez.test(value)) { return callback(new Error('手机格式失败')); } return callback(); } let dD = (rule, value, callback) => { if (value == '') { return callback(); } let rez = /^[0-9a-zA-Z]{4,11}$/; if (!rez.test(value)) { return callback(new Error('4-11位,支持数字和字母')); } return callback(); } let mob = { validator: moblieValidate, trigger: 'change' } let dDV = { validator: dD, trigger: 'change' } export let addValidate = { contactUser: [req], telphone: [req, mob], reserved1: [req], reserved2: [req], orgName: [req], email: [req, { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }], password: [req, dDV], userName: [dDV, dD], roleId: [req], isCreater: [req] }; export let editValidate = { orgName: [req], email: [req, { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }], reserved1: [req], reserved2: [req], contactUser: [req], telphone: [req, mob], isCreater: [req] } <file_sep>/src/components/common/mqtt.js import "../../utils/mqttws31.js"; import axios from '../../httpjs.js' import { Notification } from 'element-ui' import Eve from './emit' export default function mqtt() { let STATE = true; let hostname = "192.168.1.4", port = 8083, clientId = "13000000004", timeout = 5, keepAlive = 50, cleanSession = false, ssl = false, userName = "cline", password = "<PASSWORD>"; let topic = "13000000004"; let client; let element; let onConnectionLost = function (responseObject) { STATE = true; if (responseObject.errorCode !== 0) { console.log("onConnectionLost:" + responseObject.errorMessage); console.log("连接已断开"); } else { console.log("连接已断开"); Notification({ title: '成功', message: '文件生成完成,请去导出文件列表下载!!!', type: 'success', position: 'top-left' }); } }, onMessageArrived = function (message) { console.log(message, "收到消息:" + message.payloadString); Eve.$emit('upFileLoad'); client.disconnect(); // 断开连接 }, onConnect = function () { console.log("onConnected"); STATE = false; client.subscribe(topic); // 订阅主题 }; return function (url, data, that) { element = that; axios.post(url, data).then(data => { Notification.info({ title: '提示', message: '正在生成文件,请稍等……', position: 'top-left' }); if (!STATE) { return false; } let obj = data.mqttConfig; hostname = obj.ip; port = obj.port; userName = obj.userName; password = <PASSWORD>; topic = obj.topic; clientId = obj.clientId client = new window.Paho.MQTT.Client(hostname, port, clientId); //建立客户端实例 var options = { invocationContext: { host: hostname, port: port, path: client.path, clientId: clientId }, timeout: timeout, keepAliveInterval: keepAlive, cleanSession: cleanSession, useSSL: ssl, userName: userName, password: <PASSWORD>, onSuccess: onConnect, onFailure: function (e) { console.log(e); } }; client.connect(options); // 连接服务器并注册连接成功处理事件 client.onConnectionLost = onConnectionLost; // 注册连接断开处理事件 client.onMessageArrived = onMessageArrived; // 注册消息接收处理事件 }) } } <file_sep>/src/httpjs.js import axios from 'axios' import router from './router' import { Notification } from 'element-ui' import {baseurl} from './base.js' axios.interceptors.response.use((res) =>{ if(res.data.code=='200'||res.data.code=='0000'){ return Promise.resolve(res.data.data); } else if(res.data.code==409){ Notification.error({ title: '错误', message: '账户在别的地方登陆或者过期,请重新登陆!' }); router.push({ path: '/login' }) } else{ Notification.error({ title: '错误', message: res.data.msg }); return Promise.reject(res.data); } }, (error) => { //404等问题可以在这里处理. console.log(error,2222) Notification.error({ title: '错误', message: error }); return Promise.reject(error); }); axios.defaults.baseURL=baseurl; axios.defaults.withCredentials = true; axios.defaults.timeout = 100000; axios.defaults.headers['Content-Type'] = 'application/json;charset=UTF-8'; // axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'; export default axios;<file_sep>/src/components/common/initMenuList.js export function treeInitData(data, T) { data = JSON.parse(JSON.stringify(data)); function Arr(data) { let arr = []; for (let i in data) { let ooo; if (data[i].children) { ooo = Arr(data[i].children); data[i].children = ooo; } arr.push(data[i]); } return arr; } let obj = {}; for (let i = 0, len = data.length; i < len; i++) { let o = data[i]; o.disabled = T; obj[o.menuId] = o; } for (let i in obj) { let oa = obj[i]; if (obj[oa["menuParent"]]) { !obj[oa["menuParent"]].children && (obj[oa["menuParent"]].children = {}); obj[oa["menuParent"]].children[i] = oa; }else{ } } return Arr({ 1: obj[777777777] }); }
251c01d5923220d11c8034f796cdf4d6418f87ca
[ "JavaScript", "Markdown" ]
10
JavaScript
mahuan2372/nxy
c521ef9ebfba9f8941edcad37d7ee0a8237edec0
20ada5973b5f5c0f4f08fa4ffceed50c11df04df
refs/heads/master
<repo_name>lelaleite/Tugas-1<file_sep>/Tugas1-04317038.py nama = "<NAME>" nim = "04317038" umur = 18 print ("Namaku :" + nama) print ("Nimku :" + nim) print ("umur :") print (umur) print ("umurku 5 tahun lagi :") print (umur + 5)
e8c0215f103be79615e3859d544d0f11458a823f
[ "Python" ]
1
Python
lelaleite/Tugas-1
b3c22c37554fb8dd4c17b492c819c3fa46bb4719
4d76a48137ba10a0148f37c8acd323fcc3fcd3a7
refs/heads/master
<file_sep>var myApp = angular.module('myApp', ['ui.router','ui.router.state.events', 'firebase']); myApp.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){ $stateProvider .state('login',{ url:'/', templateUrl:'login.html', controller: 'loginCtrl' }) .state('registration',{ url:'/register', templateUrl:'register.html', controller: 'regCtrl' }) .state('main',{ url:'/main', templateUrl:'main.html', controller: 'mainCtrl' }); $urlRouterProvider.otherwise('/'); }]); myApp.controller('loginCtrl', ['$scope', '$location', 'myService', '$firebaseAuth','$firebaseArray', function($scope, $location, myService,$firebaseAuth, $firebaseArray){ //SETUP// // DB EMP Data /* MOCK USER DATA WITHOUT FIREBASE $scope.userInfo = [ { 'email': '<EMAIL>', 'password':'123'}, { 'email': '<EMAIL>', 'password':'123'}, { 'email': '<EMAIL>', 'password':'123'} ]; */ $scope.username = myService.getUser(); if($scope.username){ $location.path('/main'); } /*/////////// VERY IMPORTANT //// FIREBASE QUERY var ref = firebase.database().ref(); var studRef = ref.child("students"); $firebaseArray(studRef); $scope.thename = 'babo'; studRef.orderByChild('name').equalTo($scope.thename).on("child_added", function(snapshot){ console.log(snapshot.val().email); $scope.thename = snapshot.val().email; }); //////////// VERY IMPORTANT //// FIREBASE QUERY DONE*/ ////////////////// $scope.handleLogin = function(){ var username = $scope.user.email; var password = $scope.user.password; var auth = $firebaseAuth(); auth.$signInWithEmailAndPassword(username, password) .then(function(user){ console.log('success'); myService.setUser(username); $location.path('/main'); }) .catch(function(error){ console.log(error); }); /* OLD WAY of LOGIN without FIREBASE if(username && password){ console.log('login processing'); var obj = $scope.userInfo.find(function (obj) { return obj.email === username; }); if(obj){ if(obj.password == <PASSWORD>){ console.log('login success!'); myService.setUser(username); $location.path('/main'); }else{ console.log('wrong password'); } }else{ console.log('no such username'); } }else{ alert('validation problem'); }*/ }; }]); myApp.controller('mainCtrl', ['$scope','$location', 'myService', '$firebaseArray', function($scope, $location, myService, $firebaseArray){ //SETUP// // DB EMP Data $scope.username = myService.getUser(); if($scope.username){ //do nothing }else{ $location.path('/login'); } //GET USER INFO //////////// VERY IMPORTANT //// FIREBASE QUERY var ref = firebase.database().ref(); var studRef = ref.child("users"); $firebaseArray(studRef); var username = myService.getUser(); studRef.orderByChild('email').equalTo(username).on("child_added", function(snapshot){ console.log(snapshot.val().email); console.log(snapshot.val().phone); console.log(snapshot.val().username); }); //////////// VERY IMPORTANT //// FIREBASE QUERY DONE/ $scope.logout = function(){ myService.logoutUser(); } }]); myApp.controller('regCtrl', ['$scope','$location', 'myService', '$firebaseAuth', '$firebaseArray' , function($scope, $location, myService, $firebaseAuth, $firebaseArray){ //SETUP// // DB EMP Data $scope.username = myService.getUser(); if($scope.username){ //do nothing }else{ //$location.path('/login'); } $scope.handleReg = function(){ var username = $scope.user.email; var password = $<PASSWORD>; var auth = $firebaseAuth(); auth.$createUserWithEmailAndPassword(username, password) .then(function(user){ var thename = $scope.user.username; var phone = $scope.user.phone; var ref = firebase.database().ref("users"); $firebaseArray(ref).$add($scope.user); }) .catch(function(error){ console.log(error); }); } /* //FIREBASE ADD $scope.addUser = function(){ console.log('pushed'); var ref = firebase.database().ref("users"); $firebaseArray(ref).$add($scope.user) .then( function(ref){ console.log("worked"); }, function(error){ console.log(error); } ) } */ }]); myApp.service('myService', ['$location', function($location){ var user=''; return{ getUser:function(){ if(user == ''){ user = localStorage.getItem('userinfo'); } return user; }, setUser:function(value){ localStorage.setItem('userinfo', value); user = value; }, logoutUser:function(){ user =''; localStorage.removeItem('userinfo'); $location.path('/login'); } } }]);
31f4a9ef97f4589b17d3401af2083e9b88550602
[ "JavaScript" ]
1
JavaScript
yohanbae/login_firebase
2fa51d803fedef9000350d71498c4e58338e7efa
98f4456f444eab74b7a9936a18e45102f96d8c22
refs/heads/master
<file_sep>import org.junit.Test; public class TestClasses { @Test public void Test01(){ System.out.println("This is my first test"); } }
9d5ff69daea5a61c2dc7d3c315db94dfdb92e018
[ "Java" ]
1
Java
AlexandruC05/ACA-project
a51a0774534a0ce3567560cbf8a39f44e9daa693
cef46fded021bfe40ddcb53825382ea241d6f9f8
refs/heads/master
<file_sep>#!/bin/bash # check arg if [ "$#" != "1" ] || [ "$1" != "install" -a "$1" != "uninstall" ] then echo "usage: $0 <mode>" echo echo " <mode>: [ install | uninstall ]" echo exit 1 fi # install mode if [ "$1" = "install" ] then # check installation which helm > /dev/null [ "$?" = 0 ] && echo "Helm is already installed!" && exit 0 # check sudo sudo true if [ "$?" != 0 ] then echo "Root privilege check failed!" exit 1 fi # install curl https://baltocdn.com/helm/signing.asc | sudo apt-key add - sudo apt install apt-transport-https --yes echo "deb https://baltocdn.com/helm/stable/debian/ all main" | sudo tee /etc/apt/sources.list.d/helm-stable-debian.list sudo apt update sudo apt install -y helm exit $? # uninstall mode elif [ "$1" = "uninstall" ] then # check installation which helm > /dev/null [ "$?" != 0 ] && echo "Helm is already not installed!" && exit 0 # check sudo sudo true if [ "$?" != 0 ] then echo "Root privilege check failed!" exit 1 fi # uninstall if [ -f /etc/apt/sources.list.d/helm-stable-debian.list ] then sudo apt remove -y helm sudo apt autoremove -y sudo rm -f /etc/apt/sources.list.d/helm-stable-debian.list sudo apt update fi exit $? # this should not be reached else exit 255 fi <file_sep>#!/bin/bash # Before executing this script, # You'd better check the page which describe how to clean up the cluster: # https://github.com/rook/rook/blob/release-1.6/Documentation/ceph-teardown.md if [ "$#" -eq 0 ] then echo "usage: $0 <node-1-host> <node-2-host> ..." exit 1 fi # confirm wipe echo " ***** CAUTION ***** " echo " - On the given hosts: $@" echo " This script automatically deletes/wipe followings without prompt:" echo " - /var/lib/rook" echo " - /dev/mapper/ceph--*" echo " - /dev/ceph-*" echo " - And all existing cephfs partitions (ceph_bluestore)" echo echo " (For more information about the cleanup process :" echo " https://github.com/rook/rook/blob/release-1.6/Documentation/ceph-teardown.md )" echo echo " It is highly recommended that you run these commands manually," echo " if there are important data in the target hosts." echo echo -n "DO YOU REALLY WANT TO WIPE ALL ABOVE AUTOMATICALLY? [y/n]: " read CONFIRM if [ "$CONFIRM" != "Y" ] && [ "$CONFIRM" != "y" ] then echo "Cleanup is cancelled by user." exit 1 fi # repeat cleanup with all hosts for NODE in $@ do echo echo "Accessing node \"$NODE\"..." ssh -t "$NODE" bash -c 'true sudo true if [ "$?" -ne 0 ]; then echo; exit; fi echo # /var/lib/rook if [ -d "/var/lib/rook" ] then echo "Cleaning \"/var/lib/rook\"..." sudo rm -rf "/var/lib/rook" fi # /dev/mapper/ceph--* for f in /dev/mapper/ceph--* do if [ ! -e "$f" ]; then continue; fi echo "Cleaning \"$f\"..." sudo dmsetup remove "$f" sudo rm -rf "$f" done # /dev/ceph-* for f in /dev/ceph-* do if [ ! -e "$f" ]; then continue; fi echo "Cleaning \"$f\"..." sudo rm -rf "$f" done # wipe all ceph_bluestore fs CEPHFS_LIST=$(lsblk --path -rno NAME,FSTYPE | grep " ceph_bluestore$" | cut -d" " -f1) for cephfs in $CEPHFS_LIST do echo "Wiping cephfs \"$cephfs\"..." sudo wipefs -a $cephfs done ' # END OF SSH BASH -C done <file_sep># CI Utils Install Script for Kubernetes - Simple scripts for installing CI utils on on-premise Kubernetes - Tested on Ubuntu 20.04, and Kubernetes v1.21.1 - Author: <EMAIL> ## Usage - Install all - Without rook ceph (helm, gitlab-k8s, jenkins-k8s): `$ ./install-all.sh no-ceph` - With rook ceph (helm, rook-ceph-shared-storage-k8s, gitlab-k8s, jenkins-k8s): `$ ./install-all.sh install-ceph <mon-counts>` - This script will install: - Helm on local machine (need root privilege) - (If install-ceph) Rook Ceph - Shared Storage for K8s (https://github.com/rook/rook), on the namespace 'rook-ceph' - GitLab for K8s, on the namespace 'ci-gitlab' - Jenkins for K8s, on the namespace 'ci-jenkins' - <mon-counts> should be less than or equal to the worker node counts, and should be an odd number. - In case that you want to set default time zone for GitLab and Jenkins, define `$CI_TIMEZONE` by something like: `$ CI_TIMEZONE='Asia/Seoul' ./install-all.sh install-ceph 3` - Install separately: `$ ./scripts/install-(util_name).sh install` - After installing GitLab and Jenkins, initial ID/PW will be printed on terminal. - If you want them after clearing terminal outputs, execute followings: - GitLab (ID: root) - `kubectl -n ci-gitlab get secret gitlab-gitlab-initial-root-password -ojsonpath='{.data.password}' | base64 --decode; echo` - Jenkins (ID: admin) - `kubectl -n ci-jenkins get secret jenkins -ojsonpath='{.data.jenkins-admin-password}' | base64 --decode; echo` - GitLab and Jenkins will be installed as NodePort type on k8s currently. - Ports are defined as `$NODE_PORT` variable in each script. - Default ports (`$NODE_PORT`): - GitLab: 30330 - Jenkins: 30331 - In case that you want to set default time zone for GitLab or Jenkins, define `$GITLAB_TIMEZONE` or `$JENKINS_TIMEZONE` respectively by something like: `$ GITLAB_TIMEZONE='Asia/Seoul' ./scripts/install-gitlab-k8s.sh install` or `$ JENKINS_TIMEZONE='Asia/Seoul' ./scripts/install-jenkins-k8s.sh install` - Uninstall separately: `$ ./scripts/install-(util_name).sh uninstall` <file_sep>#!/bin/bash # install helm on local system for prerequesites, # and then install rook-ceph, gitlab, and jenkins on k8s. # check arg if ! [ "$1" = "install-ceph" -a "$#" = "2" ] && ! [ "$1" = "no-ceph" -a "$#" = "1" ] then echo "usage: $0 <mode>" echo echo " <mode>: [ install-ceph | no-ceph ]" echo echo " install-ceph <mon-counts>" echo " ( <mon-counts> <= (worker node counts) )" echo " ( <mon-counts> should be an odd number )" echo echo " no-ceph" echo echo " * If you have no default dynamic provisioner on k8s," echo " then [install-ceph] mode is recommended." echo exit 1 fi # install helm ./scripts/install-helm.sh install && \ # install rook ceph (shared storage), if argument install-ceph is given if [ "$1" = "install-ceph" ] then ./scripts/install-rook-ceph-shared-storage-k8s.sh install "$2" fi && \ # install and configure jenkins for k8s JENKINS_TIMEZONE=$CI_TIMEZONE ./scripts/install-jenkins-k8s.sh install && \ # install and configure gitlab for k8s GITLAB_TIMEZONE=$CI_TIMEZONE ./scripts/install-gitlab-k8s.sh install # return result code exit $? <file_sep>#!/bin/bash # Rook Ceph - Shared Storage # More info: https://github.com/rook/rook GIT_BRANCH=release-1.6 YAML_BASE_URL="https://raw.githubusercontent.com/rook/rook/$GIT_BRANCH/cluster/examples/kubernetes/ceph/" # check arg if ! [ "$1" = "install" -a "$#" = "2" ] && ! [ "$1" = "uninstall" -a "$#" = "1" ] then echo "usage: $0 <mode> [args]" echo echo " <mode>: [ install | uninstall ]" echo echo " install <mon-counts>" echo " ( <mon-counts> <= (worker node counts) )" echo " ( <mon-counts> should be an odd number )" echo echo " uninstall" echo exit 1 fi # install mode if [ "$1" = "install" ] then # get mon counts. if less than 1 or NaN, then set to 1 MON_COUNTS="$2" if ! [ "$2" -ge 1 ] 2> /dev/null then MON_COUNTS="1" fi MON_COUNTS_YAML=" apiVersion: ceph.rook.io/v1 kind: CephCluster metadata: name: rook-ceph namespace: rook-ceph spec: mon: count: $MON_COUNTS " # install yaml kubectl create -f "$YAML_BASE_URL"/common.yaml && \ kubectl create -f "$YAML_BASE_URL"/operator.yaml && \ kubectl create -f "$YAML_BASE_URL"/crds.yaml && \ kubectl create -f "$YAML_BASE_URL"/cluster.yaml && \ echo "$MON_COUNTS_YAML" | kubectl apply -f- && \ kubectl create -f "$YAML_BASE_URL"/filesystem.yaml && \ kubectl create -f "$YAML_BASE_URL"/csi/cephfs/storageclass.yaml EXIT_CODE=$? # watch for osd running if [ "$EXIT_CODE" -eq 0 ] then echo | watch -e ' PODLIST=$(kubectl get pod -n rook-ceph) echo "$PODLIST" echo echo echo " *** Waiting for OSD running... *** " echo echo " - This watch will exit automatically when a OSD is in running state." echo " - If this does not exit for more than about 10 mins, something might be wrong." echo " You can exit from here by pressing following keys: \"Ctrl + C\"" echo "$PODLIST" | tr -s " " | \ grep "^rook-ceph-osd-" | grep -v "^rook-ceph-osd-prepare-" | \ grep " Running " > /dev/null 2> /dev/null if [ $? -eq 0 ] then exit 1 fi ' fi exit "$EXIT_CODE" # uninstall mode elif [ "$1" = "uninstall" ] then # delete with yaml kubectl delete -f "$YAML_BASE_URL"/csi/cephfs/storageclass.yaml kubectl delete -f "$YAML_BASE_URL"/filesystem.yaml # set to cleanup all kubectl -n rook-ceph patch cephcluster rook-ceph --type merge -p '{"spec":{"cleanupPolicy":{"confirmation":"yes-really-destroy-data"}}}' kubectl -n rook-ceph delete cephcluster rook-ceph # kubectl delete -f "$YAML_BASE_URL"/cluster.yaml kubectl delete -f "$YAML_BASE_URL"/crds.yaml kubectl delete -f "$YAML_BASE_URL"/operator.yaml kubectl delete -f "$YAML_BASE_URL"/common.yaml for CRD in $(kubectl get crd -n rook-ceph | awk '/ceph.rook.io/ {print $1}') do kubectl get -n rook-ceph "$CRD" -o name | \ xargs -I {} kubectl patch {} --type merge -p '{"metadata":{"finalizers": [null]}}' done echo echo "*** To finish cleanup, you might also want to do cleanup on ALL K8S NODES ***" echo "*** by executing the script: cleanup-rook-ceph-on-all-nodes-after-uninstall.sh ***" # this should not be reached else exit 255 fi <file_sep>#!/bin/bash # GitLab installation for k8s TMP_YAMLFILE=".gitlab-values.yaml" K8S_NAMESPACE="ci-gitlab" # k8s gitlab using ceph provisioner (https://github.com/rook/rook.git) SC_NAME="rook-cephfs" NODE_PORT="30330" GITLAB_SVC_YAML=" apiVersion: v1 kind: Service metadata: name: gitlab-webservice-default namespace: $K8S_NAMESPACE spec: ports: - name: http-webservice nodePort: 0 port: 8080 protocol: TCP targetPort: 8080 - name: http-workhorse nodePort: $NODE_PORT port: 8181 protocol: TCP targetPort: 8181 type: NodePort " # check arg if [ "$#" != "1" ] || [ "$1" != "install" -a "$1" != "uninstall" ] then echo "usage: $0 <mode>" echo echo " <mode>: [ install | uninstall ]" echo exit 1 fi # install mode if [ "$1" = "install" ] then # check if defined provisioner is installed kubectl get sc | grep "^$SC_NAME " > /dev/null 2> /dev/null if [ "$?" != "0" ] then echo "Provisioner ($SC_NAME) does not exist." echo "Continuing with default provisioner..." SC_NAME="" fi # Timezone settings - set to default if not defined if [ -z "$GITLAB_TIMEZONE" ] then GITLAB_TIMEZONE="UTC" fi # install kubectl create ns "$K8S_NAMESPACE" helm repo add gitlab https://charts.gitlab.io/ helm repo update helm upgrade --namespace "$K8S_NAMESPACE" --install gitlab gitlab/gitlab --timeout 600s \ --set global.hosts.externalIP=127.0.0.1 \ --set global.hosts.https=false \ --set global.edition=ce \ --set global.time_zone="$GITLAB_TIMEZONE" \ --set global.storageClass="$SC_NAME" \ --set gitlab.gitaly.persistence.storageClass="$SC_NAME" \ --set gitlab-runner.install=false \ --set gitlab-runner.rbac.create=false \ --set certmanager-issuer.email=<EMAIL> \ --set certmanager.install=false \ --set prometheus.server.persistentVolume.storageClass="$SC_NAME" \ --set minio.persistence.storageClass="$SC_NAME" \ && echo "$GITLAB_SVC_YAML" | kubectl apply -n "$K8S_NAMESPACE" -f- \ && echo -e \ "\n\n==========================="\ "\n\e[31m[*** GitLab Login Info ***]\e[0m"\ "\n - ID: \e[31mroot\e[0m"\ "\n - PW: \e[30;41m$(kubectl -n $K8S_NAMESPACE get secret gitlab-gitlab-initial-root-password -ojsonpath='{.data.password}' | base64 --decode)\e[0m"\ "\n===========================\n\n" EXIT_CODE=$? # watch for webservice running if [ "$EXIT_CODE" -eq 0 ] then echo | watch -e ' PODLIST=$(kubectl get pod -n '"$K8S_NAMESPACE"') echo "$PODLIST" echo echo echo " *** Waiting for Webservice running... *** " echo echo " - This watch will exit automatically when a webservice is in running state." echo " - If this does not exit for more than about 10 mins, something might be wrong." echo " You can exit from here by pressing following keys: \"Ctrl + C\"" echo "$PODLIST" | tr -s " " | \ grep "^gitlab-webservice-default-" | \ grep " Running " > /dev/null 2> /dev/null if [ $? -eq 0 ] then exit 1 fi ' fi exit "$EXIT_CODE" # uninstall mode elif [ "$1" = "uninstall" ] then # uninstall helm uninstall -n "$K8S_NAMESPACE" gitlab kubectl delete ns "$K8S_NAMESPACE" exit $? # this should not be reached else exit 255 fi <file_sep>#!/bin/bash # Jenkins installation for k8s K8S_NAMESPACE="ci-jenkins" # k8s jenkins using ceph provisioner (https://github.com/rook/rook.git) SC_NAME="rook-cephfs" JENKINSPVC="jenkins-pvc" NODE_PORT="30331" JENKINS_YAML=" --- apiVersion: v1 kind: PersistentVolumeClaim metadata: name: $JENKINSPVC namespace: $K8S_NAMESPACE spec: storageClassName: '' accessModes: - ReadWriteOnce resources: requests: storage: 20Gi --- apiVersion: v1 kind: ServiceAccount metadata: name: $K8S_NAMESPACE namespace: $K8S_NAMESPACE --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: annotations: rbac.authorization.kubernetes.io/autoupdate: 'true' labels: kubernetes.io/bootstrapping: rbac-defaults name: $K8S_NAMESPACE rules: - apiGroups: - '*' resources: - statefulsets - services - replicationcontrollers - replicasets - podtemplates - podsecuritypolicies - pods - pods/log - pods/exec - podpreset - poddisruptionbudget - persistentvolumes - persistentvolumeclaims - jobs - endpoints - deployments - deployments/scale - daemonsets - cronjobs - configmaps - namespaces - events - secrets verbs: - create - get - watch - delete - list - patch - update - apiGroups: - '' resources: - nodes verbs: - get - list - watch - update --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: annotations: rbac.authorization.kubernetes.io/autoupdate: 'true' labels: kubernetes.io/bootstrapping: rbac-defaults name: $K8S_NAMESPACE roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: $K8S_NAMESPACE subjects: - apiGroup: rbac.authorization.k8s.io kind: Group name: system:serviceaccounts:$K8S_NAMESPACE " # check arg if [ "$#" != "1" ] || [ "$1" != "install" -a "$1" != "uninstall" ] then echo "usage: $0 <mode>" echo echo " <mode>: [ install | uninstall ]" echo exit 1 fi # install mode if [ "$1" = "install" ] then # check if defined provisioner is installed kubectl get sc | grep "^$SC_NAME " > /dev/null 2> /dev/null if [ "$?" != "0" ] then echo "Provisioner ($SC_NAME) does not exist." echo "Continuing with default provisioner..." else # set storageClass, if provisioner exists JENKINS_YAML=$(echo "$JENKINS_YAML" | sed "s/storageClassName: ''/storageClassName: $SC_NAME/g") fi #Timezone settings - set to default if not defined if [ -z "$JENKINS_TIMEZONE" ] then JENKINS_TIMEZONE="UTC" fi # install kubectl create ns "$K8S_NAMESPACE" echo "$JENKINS_YAML" | kubectl apply -f- helm repo add jenkinsci https://charts.jenkins.io helm repo update helm install jenkins -n "$K8S_NAMESPACE" jenkinsci/jenkins \ --set persistence.existingClaim="$JENKINSPVC" \ --set controller.javaOpts="-Duser.timezone=$JENKINS_TIMEZONE" \ --set controller.nodePort="$NODE_PORT" \ --set controller.serviceType=NodePort \ --set serviceAccount.create=false \ --set serviceAccount.name="$K8S_NAMESPACE" \ --set serviceAccount.annotations="{}" \ && echo -e \ "\n\n==========================="\ "\n\e[31m[*** Jenkins Login Info ***]\e[0m"\ "\n - ID: \e[31madmin\e[0m"\ "\n - PW: \e[30;41m$(kubectl -n $K8S_NAMESPACE get secret jenkins -ojsonpath='{.data.jenkins-admin-password}' | base64 --decode)\e[0m"\ "\n===========================\n\n" exit $? # uninstall mode elif [ "$1" = "uninstall" ] then helm uninstall jenkins -n "$K8S_NAMESPACE" kubectl delete ns "$K8S_NAMESPACE" kubectl delete clusterrole "$K8S_NAMESPACE" kubectl delete clusterrolebinding "$K8S_NAMESPACE" # this should not be reached else exit 255 fi
2b68ee83db14f6f82c875ca98b408559887e082b
[ "Markdown", "Shell" ]
7
Shell
snoopy3476/kube-ci-install-script
772712535bce83df195058e207108ea6c9df4164
64230b4761429a2bc680408cd777ae78d849ee6f
refs/heads/master
<repo_name>hongjiapeng/CaterManagement<file_sep>/CaterBLL/MemberTypeInfoBLL.cs using CaterDAL; using CaterModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CaterBLL { public partial class MemberTypeInfoBLL { private MemberTypeInfoDAL mtiDAL = null; public MemberTypeInfoBLL() { mtiDAL = new MemberTypeInfoDAL(); } public List<MemberTypeInfo> GetList() { return mtiDAL.GetList(); } /// <summary> /// 添加 /// </summary> /// <param name="mti"></param> /// <returns></returns> public bool Add(MemberTypeInfo mti) { return mtiDAL.Insert(mti) > 0; } public bool Update(MemberTypeInfo mti) { return mtiDAL.Update(mti) > 0; } public bool Remove(int id) { return mtiDAL.Delete(id) > 0; } } } <file_sep>/CaterBLL/MemberInfoBLL.cs using CaterDAL; using CaterModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CaterBLL { public partial class MemberInfoBLL { private MemberInfoDAL miDAL = new MemberInfoDAL(); public List<MemberInfo> Getlist(Dictionary<string, string> dic) { return miDAL.GetList(dic); } public bool Add(MemberInfo mi) { return miDAL.Insert(mi) > 0; } public bool Edit(MemberInfo mi) { return miDAL.Update(mi) > 0; } public bool Remove(int id) { return miDAL.Delete(id) > 0; } } } <file_sep>/CaterUI/FrmDishTypeInfo.cs using CaterBLL; using CaterModel; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CaterUI { public partial class FrmDishTypeInfo : Form { public FrmDishTypeInfo() { InitializeComponent(); } DishTypeInfoBLL dtiBLL = new DishTypeInfoBLL(); private DialogResult result = DialogResult.Cancel; private int rowIndex = -1;//修改后 选中行获得焦点 private void FrmDishTypeInfo_Load(object sender, EventArgs e) { LoadList(); } private void LoadList() { //设置列自动适应宽度 dgvList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; dgvList.AutoGenerateColumns = false; dgvList.DataSource = dtiBLL.GetList(); //设置某行选中 if (rowIndex >= 0) { dgvList.Rows[rowIndex].Selected = true; } } private void btnSave_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtTitle.Text)) { MessageBox.Show("标题不能为空"); txtTitle.Focus(); return; } //根据用户输入构造对象 DishTypeInfo dti = new DishTypeInfo() { DTitle = txtTitle.Text.Trim() }; if (txtId.Text.Equals("添加时无编号")) { #region 添加逻辑 if (dtiBLL.Add(dti)) { LoadList(); } else { MessageBox.Show("添加失败,请稍候重试"); } #endregion } else { #region 修改逻辑 dti.DId = Convert.ToInt32(txtId.Text); if (dtiBLL.Edit(dti)) { LoadList(); } else { MessageBox.Show("修改失败,请稍后再试!"); } #endregion } //清除控件值 txtId.Text = "添加时无编号"; txtTitle.Clear(); btnSave.Text = "添加"; this.result = DialogResult.OK; } private void btnCancel_Click(object sender, EventArgs e) { //清除控件值 txtId.Text = "添加时无编号"; txtTitle.Clear(); btnSave.Text = "添加"; } private void btnRemove_Click(object sender, EventArgs e) { //获取用户选中行的集合 var row = dgvList.SelectedRows[0]; int id = Convert.ToInt32(row.Cells[0].Value); DialogResult result = MessageBox.Show("确定要删除吗?", "提示", MessageBoxButtons.OKCancel); if (result == DialogResult.Cancel) { return; } if (dtiBLL.Remove(id)) { LoadList(); } else { MessageBox.Show("删除失败!请稍后再试!"); } this.result = DialogResult.OK; } private void FrmDishTypeInfo_FormClosing(object sender, FormClosingEventArgs e) { this.DialogResult = this.result; } private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { var row = dgvList.Rows[e.RowIndex];//行 txtId.Text = row.Cells[0].Value.ToString(); txtTitle.Text = row.Cells[1].Value.ToString(); btnSave.Text = "修改"; //记录被点击的行的索引,用于刷新后再次选中 rowIndex = e.RowIndex; } } } <file_sep>/CaterModel/HallInfo.cs using System; namespace CaterModel { public class HallInfo { /// <summary> /// HId /// </summary> public int HId { get; set; } /// <summary> /// HTitle /// </summary> public string HTitle { get; set; } /// <summary> /// HIsDelete /// </summary> public bool HIsDelete { get; set; } } } <file_sep>/CaterDAL/DishTypeInfoDAL.cs using CaterModel; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; namespace CaterDAL { public partial class DishTypeInfoDAL { /// <summary> /// 查询未删除的数据 /// </summary> /// <returns></returns> public List<DishTypeInfo> GetList() { string sql = "select DId,DTitle from DishTypeInfo where DIsDelete=0"; DataTable dt = SqlHelper.GetDataTable(sql); List<DishTypeInfo> list = null; if (dt.Rows.Count > 0) { list = new List<DishTypeInfo>(); foreach (DataRow row in dt.Rows) { list.Add(new DishTypeInfo() { DId = Convert.ToInt32(row["did"]), DTitle=row["dtitle"].ToString() }); } } return list; } public int Insert(DishTypeInfo dti) { string sql = "insert into DishTypeInfo(DTitle,DIsDelete) values(@title,0)"; SqlParameter sp = new SqlParameter("@title",dti.DTitle); return SqlHelper.ExecuteNonQuery(sql,sp); } public int Update(DishTypeInfo dti) { string sql = "update DishTypeInfo set DTitle=@title where DId=@id"; SqlParameter[] p = { new SqlParameter("@title",dti.DTitle), new SqlParameter("@id",dti.DId) }; return SqlHelper.ExecuteNonQuery(sql,p); } public int Delete(int id) { string sql = "update DishTypeInfo set DIsDelete=1 where DId=@id"; SqlParameter p = new SqlParameter("@id",id); return SqlHelper.ExecuteNonQuery(sql,p); } } } <file_sep>/CaterUI/FrmMain.cs using CaterBLL; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CaterUI { public partial class FrmMain : Form { public FrmMain() { InitializeComponent(); } OrderInfoBLL oiBLL = new OrderInfoBLL(); private void menuQuit_Click(object sender, EventArgs e) { Application.Exit(); } private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) { //将当前应用程序退出,而不仅是关闭当前窗体 Application.Exit(); } private void menuManagerInfo_Click(object sender, EventArgs e) { FrmManagerInfo formManagerInfo = FrmManagerInfo.Create();//new FormManagerInfo(); formManagerInfo.Show(); formManagerInfo.Focus();//将当前窗体获得焦点 //如果是最小化的,则恢复到正常状态 formManagerInfo.WindowState = FormWindowState.Normal; } private void FrmMain_Load(object sender, EventArgs e) { //判断登录进来的级别 确定是否显示MenuManager图标 int type = Convert.ToInt32(this.Tag); if (type==0) { //员工 //店员,管理员菜单不需要显示 menuManagerInfo.Visible = false; } LoadHallInfo(); } /// <summary> /// 加载所有的厅包信息 /// </summary> private void LoadHallInfo() { //2.1、获取所有厅包对象 HallInfoBLL hiBLL = new HallInfoBLL(); var list = hiBLL.GetList(); tcHallInfo.TabPages.Clear();//清空 TableInfoBLL tiBLL = new TableInfoBLL(); //2.2、遍历集合 向标签页中添加信息 foreach (var hi in list) { //根据厅包对象 创建标签页对象 TabPage tp = new TabPage(hi.HTitle); //3.1动态创建列表 添加到便签页上 ListView lvTableInfo = new ListView(); //添加双击事件,完成开单功能 lvTableInfo.DoubleClick += LvTableInfo_DoubleClick; //3.2、让列表使用图片 lvTableInfo.LargeImageList = imageList1; lvTableInfo.Dock = DockStyle.Fill; tp.Controls.Add(lvTableInfo); //4.1、获取当前厅包对象的所有餐桌 // select *from TableInfo where THallId= Dictionary<string, string> dic = new Dictionary<string, string>(); dic.Add("THallId", hi.HId.ToString()); var listTableInfo = tiBLL.GetList(dic); //4.2、向列表中添加餐桌信息 foreach (var ti in listTableInfo) { var lvi = new ListViewItem(ti.TTitle, ti.TIsFree ? 0 : 1); //后续操作需要用到餐桌编号,所以在这里存一下 lvi.Tag = ti.TId; lvTableInfo.Items.Add(lvi); } //2.3、将标签页加入标签容器 tcHallInfo.TabPages.Add(tp); } } private void LvTableInfo_DoubleClick(object sender, EventArgs e) { //获取被点的餐桌项 var lv1 = sender as ListView; var lvi = lv1.SelectedItems[0]; //获取餐桌编号 int tableId = Convert.ToInt32(lvi.Tag); if (lvi.ImageIndex == 0) { //当前餐桌为空闲则开单 //1、开单,向orderinfo表插入数据 //2、修改餐桌状态为占用 int orderId = oiBLL.OpenOrder(tableId); lvi.Tag = orderId; //3、更新项的图标为占用 lv1.SelectedItems[0].ImageIndex = 1; } else { //当前餐桌已经占用,则进行点菜操作 lvi.Tag = oiBLL.GetOrderIdByTableId(tableId); } //4、打开点菜窗体 FrmOrderDish frmOrderDish = new FrmOrderDish(); frmOrderDish.Tag = lvi.Tag; frmOrderDish.Show(); } private void menuTableInfo_Click(object sender, EventArgs e) { FrmTableInfo frmTableInfo = new FrmTableInfo(); frmTableInfo.Refresh += LoadHallInfo; frmTableInfo.Show(); } private void menuDishInfo_Click(object sender, EventArgs e) { FrmDishInfo frmDishInfo = new FrmDishInfo(); frmDishInfo.Show(); } private void menuOrder_Click(object sender, EventArgs e) { //先找到选中的标签页,再找到listView,再找到选中的项,项中存储了餐桌编号,由餐桌编号查到订单编号 var listView = tcHallInfo.SelectedTab.Controls[0] as ListView; if (listView.SelectedItems.Count==0) { MessageBox.Show("请先选择要结账的餐桌再结账!","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning); return; } var lvTable = listView.SelectedItems[0]; if (lvTable.ImageIndex==0) { MessageBox.Show("餐桌还未使用,无法结账!"); return; } int tableId = Convert.ToInt32(lvTable.Tag); int orderId = oiBLL.GetOrderIdByTableId(tableId); FrmOrderPay frmOrderPay = new FrmOrderPay(); frmOrderPay.Tag = orderId; frmOrderPay.Refresh += LoadHallInfo; //打开付款窗体 frmOrderPay.Show(); } private void menuMemberInfo_Click(object sender, EventArgs e) { FrmMemberInfo frmMemberInfo = new FrmMemberInfo(); if (true) { } frmMemberInfo.Show(); } } } <file_sep>/CaterUI/FrmLogin.cs using CaterBll; using CaterModel; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CaterUI { public partial class FrmLogin : Form { public FrmLogin() { InitializeComponent(); } private void btnBack_Click(object sender, EventArgs e) { this.Close(); } private void btnLogin_Click(object sender, EventArgs e) { //获取用户输入的信息 string name = txtName.Text; string pwd = txtPwd.Text; //调用代码 int type; ManagerInfoBll miBll = new ManagerInfoBll(); LoginState loginState = miBll.Login(name, pwd, out type); switch (loginState) { case LoginState.OK: FrmMain main = new FrmMain(); main.Tag = type;//将员工级别传递过去 main.Show(); //将登录窗体隐藏 this.Hide(); break; case LoginState.NameError: MessageBox.Show("用户名错误"); break; case LoginState.PwdError: MessageBox.Show("密码错误"); break; } } } } <file_sep>/CaterModel/MemberTypeInfo.cs using System; namespace CaterModel { public class MemberTypeInfo { /// <summary> /// MId /// </summary> public int MId { get; set; } /// <summary> /// MTitle /// </summary> public string MTitle { get; set; } /// <summary> /// MDiscount /// </summary> public decimal MDiscount { get; set; } /// <summary> /// MIsDelete /// </summary> public bool MIsDelete { get; set; } } } <file_sep>/CaterUI/FrmDishInfo.cs using CaterBLL; using CaterCommon; using CaterModel; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CaterUI { public partial class FrmDishInfo : Form { public FrmDishInfo() { InitializeComponent(); } private DishInfoBLL diBLL = new DishInfoBLL(); private void FrmDishInfo_Load(object sender, EventArgs e) { LoadTypeList(); LoadList(); } private void LoadTypeList() { DishTypeInfoBLL dtiBLL = new DishTypeInfoBLL(); #region 绑定查询的下拉列表 List<DishTypeInfo> list = dtiBLL.GetList(); //向list中插入数据 因为数据库中没有 “全部”这一项 所以要手动加到list中 list.Insert(0, new DishTypeInfo() { DId = 0, DTitle = "全部" }); ddlTypeSearch.DataSource = list; ddlTypeSearch.ValueMember = "did";//对应于SelectedValue属性 ddlTypeSearch.DisplayMember = "dtitle";//用于显示的值 #endregion #region 绑定添加的下拉列表 ddlTypeAdd.DataSource = dtiBLL.GetList(); ddlTypeAdd.ValueMember = "did";//做值 ddlTypeAdd.DisplayMember = "dtitle";//展示的属性 我们可以看到的 #endregion } private void LoadList() { //查询之前做一个拼接条件的操作 Dictionary<string, string> dic = new Dictionary<string, string>(); if (!string.IsNullOrEmpty(txtTitleSearch.Text.Trim())) { dic.Add("dtitle", txtTitleSearch.Text.Trim()); } if (ddlTypeSearch.SelectedValue.ToString()!="0") { dic.Add("DTypeId", ddlTypeSearch.SelectedValue.ToString()); } dgvList.AutoGenerateColumns = false; dgvList.DataSource = diBLL.GetList(dic); } private void btnSave_Click(object sender, EventArgs e) { #region 参数过滤 if (string.IsNullOrEmpty(txtTitleSave.Text)) { MessageBox.Show("标题不能为空"); txtTitleSave.Focus(); return; } if (string.IsNullOrEmpty(txtPrice.Text)) { MessageBox.Show("价格不能为空"); txtPrice.Focus(); return; } if (string.IsNullOrEmpty(txtChar.Text)) { MessageBox.Show("拼音不能为空"); txtPrice.Focus(); return; } #endregion //收集用户输入信息 DishInfo di = new DishInfo { DTitle = txtTitleSave.Text.Trim(),//名称 DTypeId = Convert.ToInt32(ddlTypeAdd.SelectedValue),//分类 DPrice = Convert.ToDecimal(txtPrice.Text.Trim()), DChar = txtChar.Text.Trim() }; if (txtId.Text.Equals("添加时无编号")) { #region 添加 if (diBLL.Add(di)) { LoadList(); } else { MessageBox.Show("逗b,咋整的啊"); } #endregion } else { #region 修改 di.DId = int.Parse(txtId.Text.Trim()); if (diBLL.Edit(di)) { LoadList(); } else { MessageBox.Show("修改失败,请稍后再试!"); } #endregion } #region 恢复控件 txtId.Text = "添加时无编号"; txtTitleSave.Clear(); txtPrice.Clear(); txtChar.Clear(); ddlTypeAdd.SelectedIndex = 0; #endregion } private void txtTitleSave_Leave(object sender, EventArgs e) { txtChar.Text = PinyinHelper.GetPinyin(txtTitleSave.Text.Trim()); } private void btnCancel_Click(object sender, EventArgs e) { txtId.Text = "添加时无编号"; txtTitleSave.Clear(); txtPrice.Clear(); txtChar.Clear(); ddlTypeAdd.SelectedIndex = 0; } private void btnRemove_Click(object sender, EventArgs e) { int id = Convert.ToInt32(dgvList.SelectedRows[0].Cells[0].Value); DialogResult result= MessageBox.Show("确定要删除吗","提示",MessageBoxButtons.OKCancel); if (result==DialogResult.Cancel) { return; } if (diBLL.Remove(id)) { LoadList(); } else { MessageBox.Show("删除失败!请稍后再试!"); } } /// <summary> /// 内容改变后 事件 也可以 Leave事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void txtTitleSearch_TextChanged(object sender, EventArgs e) { LoadList(); } private void ddlTypeSearch_SelectedIndexChanged(object sender, EventArgs e) { LoadList(); } private void btnSearchAll_Click(object sender, EventArgs e) { txtTitleSearch.Clear(); ddlTypeSearch.SelectedIndex = 0;//全部选项 LoadList(); } private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { // var row = dgvList.Rows[e.RowIndex];//行 txtId.Text= row.Cells[0].Value.ToString(); txtTitleSave.Text = row.Cells[1].Value.ToString(); ddlTypeAdd.Text= row.Cells[2].Value.ToString(); txtPrice.Text = row.Cells[3].Value.ToString(); txtChar.Text = row.Cells[4].Value.ToString(); btnSave.Text = "修改"; } private void btnAddType_Click(object sender, EventArgs e) { // FrmDishTypeInfo frmDti = new FrmDishTypeInfo(); DialogResult result= frmDti.ShowDialog(); if (result==DialogResult.OK) { LoadList(); LoadTypeList(); } } } } <file_sep>/CaterDAL/MemberTypeInfoDAL.cs using CaterModel; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CaterDAL { public partial class MemberTypeInfoDAL { /// <summary> /// 查询未删除的数据 /// </summary> /// <returns></returns> public List<MemberTypeInfo> GetList() { string sql = "select MId, MTitle, MDiscount from MemberTypeInfo where mIsDelete=0"; List<MemberTypeInfo> list = null; DataTable dt = SqlHelper.GetDataTable(sql); if (dt.Rows.Count > 0) { list = new List<MemberTypeInfo>(); foreach (DataRow row in dt.Rows) { list.Add(new MemberTypeInfo() { MId = Convert.ToInt32(row["MId"]), MTitle = row["MTitle"].ToString(), MDiscount = Convert.ToDecimal(row["MDiscount"]) }); } } return list; } /// <summary> /// 添加 /// </summary> /// <returns></returns> public int Insert(MemberTypeInfo mti) { string sql = "insert into MemberTypeInfo( [MTitle],[MDiscount],[MIsDelete]) values(@title,@discount,0)"; //为sql语句构造参数 SqlParameter[] sp = { new SqlParameter("@title",mti.MTitle), new SqlParameter("discount",mti.MDiscount) }; return SqlHelper.ExecuteNonQuery(sql,sp); } /// <summary> /// 更新 /// </summary> /// <param name="mti"></param> /// <returns></returns> public int Update(MemberTypeInfo mti) { string sql = @"update MemberTypeInfo set mtitle=@title,mdiscount=@discount where mid=@id"; SqlParameter[] sp = { new SqlParameter("@title",mti.MTitle), new SqlParameter("@discount",mti.MDiscount), new SqlParameter("@id",mti.MId) }; return SqlHelper.ExecuteNonQuery(sql,sp); } /// <summary> /// 删除 逻辑删除 /// </summary> /// <param name="id"></param> /// <returns></returns> public int Delete(int id) { //进行逻辑删除的SQL语句 string sql = "update MemberTypeInfo set mIsDelete=1 where mid=@id"; //参数 SqlParameter p = new SqlParameter("@id",id); return SqlHelper.ExecuteNonQuery(sql,p); } } } <file_sep>/CaterDAL/TableInfoDAL.cs using CaterModel; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; namespace CaterDAL { public partial class TableInfoDAL { public List<TableInfo> GetList(Dictionary<string,string> dic) { string sql = @"select ti.*,hi.HTitle from TableInfo as ti inner join HallInfo as hi on ti.THallId=hi.Hid where ti.TIsDelete=0 and HIsDelete=0"; List<SqlParameter> listP = new List<SqlParameter>(); if (dic.Count>0) { foreach (var pair in dic) { sql += " and "+pair.Key+"=@"+pair.Key; listP.Add(new SqlParameter("@"+pair.Key,pair.Value)); } } List<TableInfo> list = new List<TableInfo>(); DataTable dt = SqlHelper.GetDataTable(sql,listP.ToArray()); foreach (DataRow row in dt.Rows) { list.Add(new TableInfo() { TId = Convert.ToInt32(row["tid"]), TTitle = row["ttitle"].ToString(), HallTitle = row["htitle"].ToString(), THallId = Convert.ToInt32(row["thallid"]), TIsFree = Convert.ToBoolean(row["tisFree"]) }); } return list; } public int Insert(TableInfo ti) { string sql = @"insert into TableInfo(ttitle,THallId,TIsFree,TIsDelete) values(@title,@hid,@free,0)"; SqlParameter[] p = { new SqlParameter("@title",ti.TTitle), new SqlParameter("@hid",ti.THallId), new SqlParameter("@free",ti.TIsFree) }; return SqlHelper.ExecuteNonQuery(sql,p); } public int Update(TableInfo ti) { string sql = "update TableInfo set TTitle=@title,THallId=@hid,TIsFree=@free,TIsDelete=0 where Tid=@id"; SqlParameter[] p = { new SqlParameter("@title",ti.TTitle), new SqlParameter("@hid",ti.THallId), new SqlParameter("@free",ti.TIsFree), new SqlParameter("@id",ti.TId) }; return SqlHelper.ExecuteNonQuery(sql,p); } public int Delete(int id) { string sql = "update TableInfo set TIsDelete=1 where Tid=@id"; SqlParameter p = new SqlParameter("@id",id); return SqlHelper.ExecuteNonQuery(sql,p); } //public int SetState(int tableId,bool isFree) //{ // string sql = @"update TableInfo set TIsFree=@isfree where TId=@tid"; // SqlParameter[] p = // { // new SqlParameter("@isfree",isFree? 1:0), // new SqlParameter("@tid",tableId) // }; // return SqlHelper.ExecuteNonQuery(sql,p); //} } } <file_sep>/CaterUI/FrmHallInfo.cs using CaterBLL; using CaterModel; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CaterUI { public partial class FrmHallInfo : Form { public FrmHallInfo() { InitializeComponent(); hiBLL = new HallInfoBLL(); } private HallInfoBLL hiBLL; public event Action MyUpdateFrm; private void FrmHallInfo_Load(object sender, EventArgs e) { LoadList(); } private void LoadList() { dgvList.AutoGenerateColumns = false; dgvList.DataSource= hiBLL.GetList(); } private void btnSave_Click(object sender, EventArgs e) { HallInfo hi = new HallInfo { HTitle = txtTitle.Text.Trim() }; if (txtId.Text.Equals("添加时无编号")) { #region 添加 if (hiBLL.Add(hi)) { LoadList(); } else { MessageBox.Show("添加失败!请稍后重试!"); } #endregion } else { #region 修改 hi.HId = Convert.ToInt32(txtId.Text); if (hiBLL.Edit(hi)) { LoadList(); } else { MessageBox.Show("修改失败!请重试!"); } #endregion } txtId.Text = "添加时无编号"; txtTitle.Clear(); btnSave.Text = "添加"; MyUpdateFrm(); } private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { var row= dgvList.Rows[e.RowIndex]; txtId.Text = row.Cells[0].Value.ToString(); txtTitle.Text = row.Cells[1].Value.ToString(); btnSave.Text = "修改"; } private void btnCancel_Click(object sender, EventArgs e) { txtId.Text = "添加时无编号"; txtTitle.Clear(); btnSave.Text = "添加"; } private void btnRemove_Click(object sender, EventArgs e) { //SelectedRows[0].Cells[0].Value 选择的行的第一列的值 int id = Convert.ToInt32(dgvList.SelectedRows[0].Cells[0].Value); DialogResult result = MessageBox.Show("确定要删除吗?", "提示", MessageBoxButtons.OKCancel); if (result == DialogResult.Cancel) { return; } if (hiBLL.Remove(id)) { LoadList(); } else { MessageBox.Show("删除失败!请稍后再试!"); } //调用事件 事件中的方法都会被执行 MyUpdateFrm(); } } } <file_sep>/CaterDAL/OrderInfoDAL.cs using CaterModel; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; namespace CaterDAL { public partial class OrderInfoDAL { /// <summary> /// 开单 /// </summary> /// <param name="tableId"></param> /// <returns></returns> public int OpenOrder(int tableId) { //插入订单数据 //更新餐桌状态 //写在一起执行,只需要和数据库交互一次 //下订单 string sql = "insert into OrderInfo(ODate,IsPay,TableId) values(getdate(),0,@tid);" + //更新餐桌状态 "update TableInfo set TIsFree=0 where TId=@tid;" + //获取最新的订单编号 "select top 1 oid from OrderInfo order by oid desc"; SqlParameter p = new SqlParameter("@tid", tableId); return Convert.ToInt32(SqlHelper.ExecuteScalar(sql, p)); } /// <summary> /// 点菜 /// </summary> /// <param name="orderId">订单号</param> /// <param name="dishId">餐桌号</param> /// <returns></returns> public int OrderDishes(int orderId, int dishId) { //查询当前订单是否已经点了这道菜 string sql = "select count(*) from orderDetailInfo where orderId=@oid and dishId=@did"; SqlParameter[] ps = { new SqlParameter("@oid", orderId), new SqlParameter("@did", dishId) }; int count = Convert.ToInt32(SqlHelper.ExecuteScalar(sql, ps)); //这里又创建了一个SqlParameter对象 为什么不能用一个?、、、 SqlParameter[] p = { new SqlParameter("@oid", orderId), new SqlParameter("@did", dishId) }; if (count > 0) { //这个订单已经点过这个菜,让数量加1 sql = "update orderDetailInfo set count=count+1 where orderId=@oid and dishId=@did"; } else { //当前订单还没有点这个菜,加入这个菜 sql = @"insert into OrderDetailInfo(orderid,dishid,count) values(@oid,@did,1)"; } return SqlHelper.ExecuteNonQuery(sql, p); //“System.ArgumentException”类型的未经处理的异常在 System.Data.dll 中发生 //其他信息: 另一个 SqlParameterCollection 中已包含 SqlParameter。 } public List<OrderDetailInfo> GetDetailList(int orderId) { string sql = @"select odi.oid,di.dTitle,di.dPrice,odi.count from dishinfo as di inner join orderDetailInfo as odi on di.did=odi.dishid where odi.orderId=@orderid"; SqlParameter p = new SqlParameter("@orderid", orderId); DataTable dt = SqlHelper.GetDataTable(sql, p); List<OrderDetailInfo> list = new List<OrderDetailInfo>(); foreach (DataRow row in dt.Rows) { list.Add(new OrderDetailInfo() { OId = Convert.ToInt32(row["oid"]), DTitle = row["dtitle"].ToString(), DPrice = Convert.ToDecimal(row["dprice"]), Count = Convert.ToInt32(row["count"]) }); } return list; } public int GetOrderIdByTableId(int tableId) { string sql = "select OId from OrderInfo where IsPay=0 and TableId=@tid"; SqlParameter p = new SqlParameter("@tid", tableId); return Convert.ToInt32(SqlHelper.ExecuteScalar(sql, p)); } public int UpdateCountByOid(int oid, int count) { string sql = "update OrderDetailInfo set count=@count where oid=@oid"; SqlParameter[] sp = { new SqlParameter("@count",count), new SqlParameter("oid",oid) }; return SqlHelper.ExecuteNonQuery(sql, sp); } public decimal GetTotalMoneyByOrderId(int orderid) { string sql = @" select sum(oti.count*di.dprice) from orderdetailinfo as oti inner join dishinfo as di on oti.dishid=di.did where oti.orderid=@orderid"; SqlParameter p = new SqlParameter("@orderid", orderid); object obj = SqlHelper.ExecuteScalar(sql, p); if (obj == DBNull.Value) { return 0; } return Convert.ToDecimal(obj); } public int SetOrderMomey(int orderid, decimal money) { string sql = "update orderinfo set omoney=@money where oid=@oid"; SqlParameter[] ps = { new SqlParameter("@money", money), new SqlParameter("@oid", orderid) }; return SqlHelper.ExecuteNonQuery(sql, ps); } public int DeleteDetailById(int oid) { string sql = "delete from orderDetailInfo where oid=@oid"; SqlParameter p = new SqlParameter("@oid", oid); return SqlHelper.ExecuteNonQuery(sql, p); } public int Pay(bool isUserBalance, int memberId, decimal payMoney, int orderId, decimal discount) { //创建数据库连接对象 using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CaterConn"].ConnectionString)) { int result = 0; //由数据库链接对象创建事务 conn.Open(); SqlTransaction tran = conn.BeginTransaction(); //创建Command对象 SqlCommand cmd = new SqlCommand(); //将命令对象启用事务 cmd.Transaction = tran; //执行各命令 string sql = string.Empty; SqlParameter[] sp; try { //1、根据是否使用余额决定扣款方式 if (isUserBalance) { //使用余额 199.5300 sql = "update MemberInfo set MMoney=MMoney-@payMoney where mid=@mid"; sp = new SqlParameter[] { new SqlParameter("@payMoney", payMoney), new SqlParameter("@mid", memberId) }; cmd.CommandText = sql; cmd.Parameters.AddRange(sp); result += cmd.ExecuteNonQuery(); } //2、将订单状态为IsPage=1 sql = "update orderInfo set isPay=1,memberId=@mid,discount=@discount where oid=@oid"; sp = new SqlParameter[] { new SqlParameter("@mid", memberId), new SqlParameter("@discount", discount), new SqlParameter("@oid", orderId) }; cmd.CommandText = sql; cmd.Parameters.Clear(); cmd.Parameters.Add(sp); result += cmd.ExecuteNonQuery(); //3、将餐桌状态IsFree=1 sql = "update tableInfo set tIsFree=1 where tid=(select tableId from orderinfo where oid=@oid)"; //SqlParameter p = new SqlParameter(""); sp = new SqlParameter[] { new SqlParameter("@oid", orderId) }; cmd.CommandText = sql; cmd.Parameters.Clear(); cmd.Parameters.Add(sp); result += cmd.ExecuteNonQuery(); //提交事务 tran.Commit(); } catch (Exception) { result = 0; //回滚事务 tran.Rollback(); throw; } return result; } } } } <file_sep>/CaterUI/FrmTableInfo.cs using CaterBLL; using CaterModel; using CaterUI; using System; using System.Collections.Generic; using System.Windows.Forms; namespace CaterUI { public partial class FrmTableInfo : Form { public FrmTableInfo() { InitializeComponent(); } public event Action Refresh; private TableInfoBLL tiBLL = new TableInfoBLL(); private void FrmTableInfo_Load(object sender, EventArgs e) { LoadTypeList(); LoadList(); } private void LoadTypeList() { HallInfoBLL hiBLL = new HallInfoBLL(); #region 绑定查询的下拉表 var list = hiBLL.GetList(); list.Insert(0, new HallInfo() { HId = 0, HTitle = "全部" }); ddlHallSearch.DataSource = list; ddlHallSearch.DisplayMember = "htitle"; ddlHallSearch.ValueMember = "hid"; List<DdlModel> listDdl = new List<DdlModel>() { new DdlModel("-1","全部"), new DdlModel("1","空闲"), new DdlModel("0","使用中") }; ddlFreeSearch.DataSource = listDdl; ddlFreeSearch.ValueMember = "id"; ddlFreeSearch.DisplayMember = "title"; #endregion #region 绑定添加的下拉表 ddlHallAdd.DataSource = hiBLL.GetList(); ddlHallAdd.ValueMember = "hid"; ddlHallAdd.DisplayMember = "htitle"; #endregion } private void LoadList() { Dictionary<string, string> dic = new Dictionary<string, string>(); if (ddlHallSearch.SelectedIndex>0) { dic.Add("tHallId",ddlHallSearch.SelectedValue.ToString()); } if (ddlFreeSearch.SelectedIndex>0) { dic.Add("tIsFree",ddlFreeSearch.SelectedValue.ToString()); } dgvList.AutoGenerateColumns = false; dgvList.DataSource = tiBLL.GetList(dic); } private void dgvList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex == 3) { e.Value = Convert.ToBoolean(e.Value) ? "√" : "×"; } } private void btnSave_Click(object sender, EventArgs e) { //接受用户输入值 构造对象 TableInfo ti = new TableInfo() { TTitle=txtTitle.Text.Trim(), THallId=Convert.ToInt32(ddlHallAdd.SelectedValue), TIsFree=rbFree.Checked }; if (txtId.Text.Equals("添加时无编号")) { #region 添加 if (string.IsNullOrEmpty(txtTitle.Text.Trim())) { MessageBox.Show("名称不能为空"); txtTitle.Focus(); return; } if (tiBLL.Add(ti)) { LoadList(); } else { MessageBox.Show("添加失败!请稍后重试!"); } #endregion } else { #region 修改 ti.TId = int.Parse(txtId.Text); if (tiBLL.Edit(ti)) { LoadList(); } else { MessageBox.Show("修改失败!请稍后重试!"); } #endregion } #region 恢复控件值 txtId.Text = "添加时无编号"; txtTitle.Clear(); ddlHallAdd.SelectedIndex = 0; rbFree.Checked = true; btnSave.Text = "添加"; #endregion Refresh(); } private void btnSearchAll_Click(object sender, EventArgs e) { ddlHallSearch.SelectedIndex = 0; ddlFreeSearch.SelectedIndex = 0; } private void ddlHallSearch_SelectedIndexChanged(object sender, EventArgs e) { LoadList(); } private void ddlFreeSearch_SelectedIndexChanged(object sender, EventArgs e) { LoadList(); } private void btnRemove_Click(object sender, EventArgs e) { int id=Convert.ToInt32(dgvList.SelectedRows[0].Cells[0].Value); DialogResult result = MessageBox.Show("确定要删除吗?","提示",MessageBoxButtons.OKCancel); if (result==DialogResult.Cancel) { return; } if (tiBLL.Remove(id)) { LoadTypeList(); } else { MessageBox.Show("删除失败!请稍后重试!"); } Refresh(); } private void btnCancel_Click(object sender, EventArgs e) { txtId.Text = "添加时无编号"; txtTitle.Clear(); ddlHallAdd.SelectedIndex = 0; rbFree.Checked = true; btnSave.Text = "添加"; } private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { var row = dgvList.Rows[e.RowIndex]; txtId.Text = row.Cells[0].Value.ToString(); txtTitle.Text = row.Cells[1].Value.ToString(); ddlHallAdd.Text = row.Cells[2].Value.ToString(); if (Convert.ToBoolean(row.Cells[3].Value)) { rbFree.Checked = true; } else { rbUnFree.Checked = true; } btnSave.Text ="修改"; } private void btnAddHall_Click(object sender, EventArgs e) { FrmHallInfo frmHallInfo = new FrmHallInfo(); frmHallInfo.MyUpdateFrm += LoadTypeList; frmHallInfo.MyUpdateFrm += LoadList; frmHallInfo.Show(); } } } <file_sep>/CaterUI/FrmMemberInfo.cs using CaterBLL; using CaterModel; using System; using System.Collections.Generic; using System.Windows.Forms; namespace CaterUI { public partial class FrmMemberInfo : Form { public FrmMemberInfo() { InitializeComponent(); } MemberInfoBLL miBLL = new MemberInfoBLL(); private void FrmMemberInfo_Load(object sender, EventArgs e) { LoadList(); //加载会员分类信息 LoadTypeList(); } /// <summary> /// 加载会员类型表 /// </summary> private void LoadTypeList() { MemberTypeInfoBLL mtiBll = new MemberTypeInfoBLL(); List<MemberTypeInfo> list = mtiBll.GetList(); ddlType.DataSource = list; //设置显示值 ddlType.DisplayMember = "mtitle"; //设置value值 ddlType.ValueMember = "mid"; } /// <summary> /// 加载数据 /// </summary> private void LoadList() { //使用键值对存储条件 Dictionary<string, string> dic = new Dictionary<string, string>(); //收集用户名信息 if (!string.IsNullOrEmpty(txtNameSearch.Text)) { //需要根据名称搜索 dic.Add("mname", txtNameSearch.Text.Trim());//key 属性名 value } //手机电话信息 if (!string.IsNullOrEmpty(txtPhoneSearch.Text)) { // dic.Add("mphone", txtPhoneSearch.Text.Trim()); } //根据条件进行查询 dgvList.AutoGenerateColumns = false; dgvList.DataSource = miBLL.Getlist(dic); //设置某行选中 if (dgvSelectedIndex>-1) { dgvList.Rows[dgvSelectedIndex].Selected = true; } } private void btnSearchAll_Click(object sender, EventArgs e) { txtNameSearch.Clear(); txtPhoneSearch.Clear(); LoadList(); } /// <summary> /// 失去焦点事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void txtNameSearch_Leave(object sender, EventArgs e) { LoadList(); } /// <summary> /// 内容改变事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void txtPhoneSearch_TextChanged(object sender, EventArgs e) { LoadList(); } /// <summary> /// 删除选中的行的数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnRemove_Click(object sender, EventArgs e) { var rows= dgvList.SelectedRows; if (rows.Count>0) { //提示 DialogResult dialog= MessageBox.Show("确定要删除吗?","提示",MessageBoxButtons.OKCancel); if (dialog==DialogResult.Cancel) { return; } //获取选中的行的编号 int id= Convert.ToInt32(dgvList.SelectedRows[0].Cells[0].Value); if (miBLL.Remove(id)) { LoadList(); } else { MessageBox.Show("删除失败!请稍后重试"); } } else { MessageBox.Show("请先选择要删除的行!"); } } private int dgvSelectedIndex = -1; private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { dgvSelectedIndex = e.RowIndex; //拿到选中的行 var row = dgvList.Rows[e.RowIndex]; //将行中的数据显示在控件上 txtId.Text = row.Cells[0].Value.ToString(); txtNameAdd.Text= row.Cells[1].Value.ToString(); ddlType.Text = row.Cells[2].Value.ToString(); txtPhoneAdd.Text= row.Cells[3].Value.ToString(); txtMoney.Text= row.Cells[4].Value.ToString(); btnSave.Text = "修改"; } private void btnCance_Click(object sender, EventArgs e) { txtId.Text = "添加时无编号"; txtNameAdd.Clear(); txtPhoneAdd.Clear(); txtMoney.Clear(); ddlType.SelectedIndex = 0; btnSave.Text = "添加"; } private void btnSave_Click(object sender, EventArgs e) { //值的有效性判断 if (string.IsNullOrEmpty(txtNameAdd.Text)) { MessageBox.Show("请输入会员姓名"); txtNameAdd.Focus(); return; } //接受用户输入的数据 MemberInfo mi = new MemberInfo { MName = txtNameAdd.Text.Trim(), MPhone = txtPhoneAdd.Text.Trim(), MMoney = Convert.ToDecimal(txtMoney.Text.Trim()), MTypeId = Convert.ToInt32(ddlType.SelectedValue) }; if (txtId.Text.Equals("添加时无编号")) { #region 添加逻辑 if (miBLL.Add(mi)) { LoadList(); } else { MessageBox.Show("添加失败,请稍后再试"); } #endregion } else { #region 修改逻辑 mi.MId = int.Parse(txtId.Text); if (miBLL.Edit(mi)) { LoadList(); } else { MessageBox.Show("修改失败 请稍后重试!"); } #endregion } //恢复控件的值 txtId.Text = "添加时无编号"; txtNameAdd.Clear(); txtPhoneAdd.Clear(); txtMoney.Clear(); ddlType.SelectedIndex = 0; btnSave.Text = "添加"; } private void btnAddType_Click(object sender, EventArgs e) { FrmMemberTypeInfo frmMti = new FrmMemberTypeInfo(); //以模态窗口打开分类管理 DialogResult result= frmMti.ShowDialog(); //根据返回的值,判断是否要更新下拉列表 if (result==DialogResult.OK) { LoadTypeList(); LoadList(); } } } } <file_sep>/CaterDAL/OrderInfoBLL.cs namespace CaterDAL { public partial class OrderInfoBLL { private OrderInfoDAL oiDAL = new OrderInfoDAL(); public int KaiDan(int tableId) { return oiDAL.OpenOrder(tableId); } public bool OpenOrder(int tableId) { return oiDAL.OpenOrder(tableId)>0; } } } <file_sep>/CaterModel/TableInfo.cs using System; namespace CaterModel { public partial class TableInfo { /// <summary> /// TId /// </summary> public int TId { get; set; } /// <summary> /// TTitle /// </summary> public string TTitle { get; set; } /// <summary> /// THallId /// </summary> public int THallId { get; set; } /// <summary> /// TIsFree /// </summary> public bool TIsFree { get; set; } /// <summary> /// TIsDelete /// </summary> public bool TIsDelete { get; set; } } } <file_sep>/CaterModel/MemberInfo.cs using System; namespace CaterModel { public partial class MemberInfo { /// <summary> /// MId /// </summary> public int MId { get; set; } /// <summary> /// MName /// </summary> public string MName { get; set; } /// <summary> /// MPhone /// </summary> public string MPhone { get; set; } /// <summary> /// MMoney /// </summary> public decimal MMoney { get; set; } /// <summary> /// MTypeId /// </summary> public int MTypeId { get; set; } /// <summary> /// MIsDelete /// </summary> public bool MIsDelete { get; set; } } } <file_sep>/CaterModel/OrderDetailInfo.cs using System; namespace CaterModel { public partial class OrderDetailInfo { /// <summary> /// OId /// </summary> public int OId { get; set; } /// <summary> /// OrderId /// </summary> public int OrderId { get; set; } /// <summary> /// DishId /// </summary> public int DishId { get; set; } /// <summary> /// Count /// </summary> public int Count { get; set; } } } <file_sep>/CaterBLL/ManagerInfoBll.cs using System.Collections.Generic; using CaterModel; using CaterDAL; using System; using CaterCommon; namespace CaterBll { public partial class ManagerInfoBll { //创建数据层对象 private ManagerInfoDAL miDal = new ManagerInfoDAL(); public List<ManagerInfo> GetList() { //调用查询方法 return miDal.GetList(); } public bool Add(ManagerInfo mi) { //调用dal层的insert方法,完成插入操作 return miDal.Insert(mi) > 0; } public bool Edit(ManagerInfo mi) { return miDal.Update(mi) > 0; } public bool Remove(int id) { return miDal.Delete(id) > 0; } public LoginState Login(string name, string pwd, out int type) { //设置type默认值,如果为此值时,不会使用 type = -1; //根据用户名进行对象的查询 ManagerInfo mi = miDal.GetByName(name); if (mi==null) { //用户名错误 return LoginState.NameError; } else { //用户名正确 if (mi.MPwd.Equals(MD5Helper.MD5Encrypt(pwd))) { //密码正确 //登录成功 type = mi.MType; return LoginState.OK; } else { //密码错误 return LoginState.PwdError; } } } } } <file_sep>/CaterUI/FrmOrderPay.cs using CaterBLL; using CaterModel; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CaterUI { public partial class FrmOrderPay : Form { public FrmOrderPay() { InitializeComponent(); } private int orderId; private OrderInfoBLL oiBLL = new OrderInfoBLL(); public event Action Refresh; private void FrmOrderPay_Load(object sender, EventArgs e) { //获取传递过来的订单编号 orderId = Convert.ToInt32(this.Tag); gbMember.Enabled = false; GetMoneyByOrderId(); } private void GetMoneyByOrderId() { lblPayMoney.Text=lblPayMoneyDiscount.Text= oiBLL.GetTotalMoneyByOrderId(orderId).ToString(); } private void btnOrderPay_Click(object sender, EventArgs e) { //1、根据是否使用余额决定扣款方式 //2、将订单状态改为IsPage=1 //3、将餐桌状态改为IsFree=1 if (oiBLL.Pay(cbkMoney.Checked,int.Parse(txtId.Text),Convert.ToDecimal(lblPayMoneyDiscount.Text),orderId,Convert.ToDecimal(lblDiscount.Text))) { //MessageBox.Show("结账成功!"); Refresh();//刷新UI Close(); } else { MessageBox.Show("结账失败!"); } } private void cbkMember_CheckedChanged(object sender, EventArgs e) { gbMember.Enabled = cbkMember.Checked; } private void txtId_Leave(object sender, EventArgs e) { LoadMemberInfo(); } /// <summary> /// 加载会员信息 /// </summary> private void LoadMemberInfo() { //根据会员编号和会员电话进行查询 Dictionary<string, string> dic = new Dictionary<string, string>(); if (!string.IsNullOrEmpty(txtId.Text)) { dic.Add("mid", txtId.Text); } if (!string.IsNullOrEmpty(txtPhone.Text)) { dic.Add("mPhone", txtPhone.Text); } MemberInfoBLL miBLL = new MemberInfoBLL(); var list = miBLL.Getlist(dic); if (list.Count > 0) { //根据信息查到了会员 MemberInfo mi = list[0]; lblMoney.Text = mi.MMoney.ToString(); lblTypeTitle.Text = mi.MTypeTitle; lblDiscount.Text = mi.MDisCount.ToString(); //计算折扣价 lblPayMoneyDiscount.Text = (Convert.ToDecimal(lblPayMoney.Text) * Convert.ToDecimal(lblDiscount.Text)).ToString(); } else { MessageBox.Show("会员信息有误!","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning); } } private void txtPhone_Leave(object sender, EventArgs e) { LoadMemberInfo(); } private void btnCancel_Click(object sender, EventArgs e) { } } } <file_sep>/CaterModel/LoginState.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CaterModel { public enum LoginState { OK, NameError, PwdError } } <file_sep>/CaterUI/FrmMemberTypeInfo.cs using CaterBLL; using CaterModel; using CaterUI; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace CaterUI { public partial class FrmMemberTypeInfo : Form { public FrmMemberTypeInfo() { InitializeComponent(); } MemberTypeInfoBLL mtiBLL = new MemberTypeInfoBLL(); private DialogResult result = DialogResult.Cancel; private void FrmMemberTypeInfo_Load(object sender, EventArgs e) { LoadList(); } private void LoadList() { //禁用列表的自动生成 dgvList.AutoGenerateColumns = false; //调用方法获取数据,绑定到列表的数据源上 dgvList.DataSource = mtiBLL.GetList(); } private void btnCancel_Click(object sender, EventArgs e) { //还原控件 txtId.Text = "添加时无编号"; txtDiscount.Clear(); txtTitle.Clear(); btnSave.Text = "添加"; } /// <summary> /// 删除选中的行 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnRemove_Click(object sender, EventArgs e) { //获取选中行的编号 var row= dgvList.SelectedRows[0]; int id= Convert.ToInt32(row.Cells[0].Value); DialogResult dialog= MessageBox.Show("确定要删除吗?","提示",MessageBoxButtons.OKCancel); if (dialog==DialogResult.Cancel) { return; } //进行删除 if (mtiBLL.Remove(id)) { LoadList(); } else { MessageBox.Show("删除失败,请稍后再试"); } result = DialogResult.OK; } private void btnSave_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtId.Text) || string.IsNullOrEmpty(txtDiscount.Text)) { MessageBox.Show("标题或折扣不能为空"); return; } //接受用户输入的值 构造对象 MemberTypeInfo mti = new MemberTypeInfo() { MTitle = txtTitle.Text, MDiscount = Convert.ToDecimal(txtDiscount.Text) }; if (txtId.Text.Equals("添加时无编号")) { #region 调用添加方法 if (mtiBLL.Add(mti)) { LoadList(); } else { MessageBox.Show("添加失败!请重试"); } #endregion } else { #region 修改 mti.MId = int.Parse(txtId.Text); //调用修改方法 if (mtiBLL.Update(mti)) { LoadList(); } else { MessageBox.Show("修改失败 请稍后重试"); } #endregion } //还原控件 txtId.Text = "添加时无编号"; txtDiscount.Clear(); txtTitle.Clear(); btnSave.Text = "添加"; result = DialogResult.OK; } private void FrmMemberTypeInfo_FormClosing(object sender, FormClosingEventArgs e) { this.DialogResult = result; } private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { DataGridViewRow row = dgvList.Rows[e.RowIndex];//行 //找列 txtId.Text = row.Cells[0].Value.ToString(); txtTitle.Text = row.Cells[1].Value.ToString(); txtDiscount.Text = row.Cells[2].Value.ToString(); btnSave.Text = "修改"; } } } <file_sep>/CaterDAL/ManagerInfoDAL.cs using System; using System.Collections.Generic; using System.Data; using CaterModel; using System.Data.SqlClient; using CaterCommon; namespace CaterDAL { public partial class ManagerInfoDAL { /// <summary> /// 查询获取结果集 /// </summary> /// <returns></returns> public List<ManagerInfo> GetList() { //构造要查询的sql语句 string sql = "select * from ManagerInfo"; //使用helper进行查询,得到结果 DataTable dt = SqlHelper.GetDataTable(sql); //将dt中的数据转存到list中 List<ManagerInfo> list=new List<ManagerInfo>(); foreach (DataRow row in dt.Rows) { list.Add(new ManagerInfo() { MId = Convert.ToInt32(row["mid"]), MName = row["mname"].ToString(), MPwd = row["mpwd"].ToString(), MType = Convert.ToInt32(row["mtype"]) }); } //将集合返回 return list; } /// <summary> /// 根据用户名查询用户信息 /// </summary> /// <param name="name"></param> /// <returns></returns> public ManagerInfo GetByName(string name) { //定义一个对象 ManagerInfo mi = null; //构造语句 string sql = "select * from managerInfo where mname=@name"; //为语句构造参数 SqlParameter p = new SqlParameter("@name", name); //执行查询得到结果 DataTable dt = SqlHelper.GetDataTable(sql, p); //判断是否根据用户名查找到了对象 if (dt.Rows.Count > 0) { //用户名存在 mi = new ManagerInfo() { MId = Convert.ToInt32(dt.Rows[0][0]), MName = name, MPwd = dt.Rows[0][2].ToString(), MType = Convert.ToInt32(dt.Rows[0][3]) }; } else { //用户名不存在 } return mi; } /// <summary> /// 插入数据 /// </summary> /// <param name="mi">ManagerInfo类型的对象</param> /// <returns></returns> public int Insert(ManagerInfo mi) { //构造insert语句 string sql = "insert into ManagerInfo(mname,mpwd,mtype) values(@name,@pwd,@type)"; //构造sql语句的参数 SqlParameter[] ps = //使用数组初始化器 { new SqlParameter("@name", mi.MName), new SqlParameter("@pwd", MD5Helper.MD5Encrypt(mi.MPwd)),//将密码进行md5加密 new SqlParameter("@type", mi.MType) }; //执行插入操作 return SqlHelper.ExecuteNonQuery(sql, ps); } /// <summary> /// 修改管理员,特别注意:密码 /// </summary> /// <param name="mi"></param> /// <returns></returns> public int Update(ManagerInfo mi) { //为什么要进行密码的判断: //答:因为密码值是经过md5加密存储的,当修改时,需要判断用户是否改了密码,如果没有改,则不变,如果改了,则重新进行md5加密 //定义参数集合,可以动态添加元素 List<SqlParameter> listPs=new List<SqlParameter>(); //构造update的sql语句 string sql = "update ManagerInfo set mname=@name"; listPs.Add(new SqlParameter("@name",mi.MName)); //判断是否修改密码 if (!mi.MPwd.Equals("这是原来的密码吗")) { sql += ",mpwd=@pwd"; listPs.Add(new SqlParameter("@pwd",MD5Helper.MD5Encrypt(mi.MPwd))); } //继续拼接语句 sql+=",mtype=@type where mid=@id"; listPs.Add(new SqlParameter("@type",mi.MType)); listPs.Add(new SqlParameter("@id",mi.MId)); //执行语句并返回结果 return SqlHelper.ExecuteNonQuery(sql, listPs.ToArray()); } /// <summary> /// 根据编号删除管理员 /// </summary> /// <param name="id"></param> /// <returns></returns> public int Delete(int id) { //构造删除的sql语句 string sql = "delete from ManagerInfo where mid=@id"; //根据语句构造参数 SqlParameter p =new SqlParameter("@id",id); //执行操作 return SqlHelper.ExecuteNonQuery(sql, p); } } } <file_sep>/CaterUI/FrmOrderDish.cs using CaterBLL; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CaterUI { public partial class FrmOrderDish : Form { public FrmOrderDish() { InitializeComponent(); } OrderInfoBLL oiBLL = new OrderInfoBLL(); private void FrmOrderDish_Load(object sender, EventArgs e) { LoadDishType(); LoadDishInfo(); LoadDetailList(); } private void LoadDishType() { DishTypeInfoBLL dtiBLL = new DishTypeInfoBLL(); var list = dtiBLL.GetList(); list.Insert(0, new CaterModel.DishTypeInfo() { DId = 0, DTitle = "全部" }); ddlType.ValueMember = "did"; ddlType.DisplayMember = "dtitle"; ddlType.DataSource = list; } private void LoadDishInfo() { //拼接查询条件 Dictionary<string, string> dic = new Dictionary<string, string>(); if (txtTitle.Text != "") { dic.Add("dchar", txtTitle.Text); } if (ddlType.SelectedValue.ToString() != "0") { dic.Add("dtypeid", ddlType.SelectedValue.ToString()); } DishInfoBLL diBLL = new DishInfoBLL(); //查询菜品 显示在表格中 dgvAllDish.AutoGenerateColumns = false; dgvAllDish.DataSource = diBLL.GetList(dic); } private void GetTotalMoneyByOrderId() { int orderId = Convert.ToInt32(this.Tag); lblMoney.Text= oiBLL.GetTotalMoneyByOrderId(orderId).ToString(); } private void txtTitle_TextChanged(object sender, EventArgs e) { LoadDishInfo(); } private void ddlType_SelectedIndexChanged(object sender, EventArgs e) { LoadDishInfo(); } private void dgvAllDish_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { //点菜 //订单编号 int orderId = Convert.ToInt32(this.Tag); //菜单编号 int dishId = Convert.ToInt32(dgvAllDish.Rows[e.RowIndex].Cells[0].Value); //执行点菜操作 if (oiBLL.OrderDishes(orderId, dishId)) { //点餐成功 LoadDetailList(); } } /// <summary> /// 加载已点的菜(详单信息) /// </summary> private void LoadDetailList() { int orderId = Convert.ToInt32(this.Tag); dgvOrderDetail.AutoGenerateColumns = false; dgvOrderDetail.DataSource = oiBLL.GetDetailList(orderId); GetTotalMoneyByOrderId(); } private void dgvOrderDetail_CellEndEdit(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 2) { //停止编辑数量列,才进行更改 //修改的行 var row = dgvOrderDetail.Rows[e.RowIndex]; //获取oid int oid = Convert.ToInt32(row.Cells[0].Value); //获取数量 int count = Convert.ToInt32(row.Cells[2].Value); //执行更新操作 oiBLL.UpdateCountByOid(oid, count); //重新计算总价 GetTotalMoneyByOrderId(); } } /// <summary> /// 下单 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnOrder_Click(object sender, EventArgs e) { //获取订单编号 int orderId = Convert.ToInt32(this.Tag); //获取总金额 decimal money = Convert.ToDecimal(lblMoney.Text); //更新订单 if (oiBLL.SetOrderMoney(orderId, money)) { MessageBox.Show("下单成功!"); } else { MessageBox.Show("卧槽,咋搞的啊!"); } } /// <summary> /// 删除选中项 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnRemove_Click(object sender, EventArgs e) { //如果选的不是一行 而是一个单元格 给个提示---------------- if (true) { //MessageBox.Show("Test"); } DialogResult result = MessageBox.Show("确定要删除吗?", "提示", MessageBoxButtons.OKCancel); if (result == DialogResult.Cancel) { return; } //dgvOrderDetail.SelectedRows[0] 选中的那一行 //获取编号 int oid = Convert.ToInt32(dgvOrderDetail.SelectedRows[0].Cells[0].Value); //执行删除 if (oiBLL.DeleteDetailById(oid)) { LoadDetailList(); } else { MessageBox.Show("删除失败!"); } } } } <file_sep>/CaterCommon/PinyinHelper.cs using Microsoft.International.Converters.PinYinConverter; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CaterCommon { public partial class PinyinHelper { public static string GetPinyin(string s) { string s1 = string.Empty; try { foreach (char c in s) { ChineseChar cc = new ChineseChar(c); s1 += cc.Pinyins[0][0]; #region 分开写 //string py1 = cc.Pinyins[0];//多音字中的第一个拼音(从集合中拿元素) //char c1 = py1[0];//获取首字母 //s1 += c1; #endregion } } catch { } return s1; } } } <file_sep>/CaterModel/OtherClass.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CaterModel { public partial class MemberInfo { public string MTypeTitle { get; set; } public decimal MDisCount { get; set; } } public partial class DishInfo { public string DTypeTitle { get; set; } } public partial class TableInfo { public string HallTitle { get; set; } } public partial class OrderDetailInfo { public string DTitle { get; set; } public decimal DPrice { get; set; } } } <file_sep>/CaterModel/DishTypeInfo.cs using System; namespace CaterModel { public class DishTypeInfo { /// <summary> /// DId /// </summary> public int DId { get; set; } /// <summary> /// DTitle /// </summary> public string DTitle { get; set; } /// <summary> /// DIsDelete /// </summary> public bool DIsDelete { get; set; } } } <file_sep>/CaterDAL/DishInfoDAL.cs using CaterModel; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; namespace CaterDAL { public partial class DishInfoDAL { public List<DishInfo> GetList(Dictionary<string, string> dic) { #region 注释 //select* from DishInfo--DTypeId //select* from DishTypeInfo--DId //--编号 名称 分类 价格 拼音 //select* from DishInfo,DishTypeInfo where DishInfo.DTypeId = DishTypeInfo.DId //--1 梅菜扣肉 30.00 MCKR 1 0 1 鲁菜 0 //--2 猪肉炖粉条 20.00 ZRDFT 4 0 4 粤菜 0 #endregion string sql = @"select di.*,dti.dtitle as dTypeTitle from dishinfo as di inner join dishtypeinfo as dti on di.dtypeid=dti.did where di.dIsDelete=0 and dti.dIsDelete=0"; List<SqlParameter> listP = new List<SqlParameter>(); //条件筛选 if (dic.Count > 0) { //sql += " and di.属性 like '%值%'"; foreach (var pair in dic) { //sql += " and dt."+pair.Key+" like '%"+pair.Value+"'%"; sql += " and di." + pair.Key + " like @" + pair.Key; listP.Add(new SqlParameter("@" + pair.Key, "%" + pair.Value + "%"));//@dtitle,%abc% } } List<DishInfo> list = new List<DishInfo>(); DataTable dt = SqlHelper.GetDataTable(sql, listP.ToArray()); foreach (DataRow row in dt.Rows) { list.Add(new DishInfo() { DId = Convert.ToInt32(row["DId"]), DTitle = row["dtitle"].ToString(), DTypeTitle = row["DTypeTitle"].ToString(), DChar = row["DChar"].ToString(), DPrice = Convert.ToDecimal(row["DPrice"]) }); } return list; } public int Insert(DishInfo di) { string sql = @"insert into DishInfo(dtitle,dtypeid,dprice,dchar,disdelete) values(@title,@tid,@price,@dchar,0)"; SqlParameter[] p = { new SqlParameter("@title",di.DTitle), new SqlParameter("@tid",di.DTypeId), new SqlParameter("@price",di.DPrice), new SqlParameter("@dchar",di.DChar) }; return SqlHelper.ExecuteNonQuery(sql, p); } public int Update(DishInfo di) { string sql = @"update DishInfo set dtitle=@title,dtypeid=@tid, dprice=@price,dchar=@dchar where did=@id"; SqlParameter[] p = { new SqlParameter("@title",di.DTitle), new SqlParameter("@tid",di.DTypeId), new SqlParameter("@price",di.DPrice), new SqlParameter("@dchar",di.DChar), new SqlParameter("@id",di.DId) }; return SqlHelper.ExecuteNonQuery(sql, p); } public int Delete(int id) { string sql = "update DishInfo set DisDelete=1 where Did=@id"; SqlParameter p = new SqlParameter("@id",id); return SqlHelper.ExecuteNonQuery(sql,p); } } } <file_sep>/CaterBLL/HallInfoBLL.cs using CaterDAL; using CaterModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CaterBLL { public partial class HallInfoBLL { private HallInfoDAL hiDAL; public HallInfoBLL() { hiDAL = new HallInfoDAL(); } public List<HallInfo> GetList() { return hiDAL.GetList(); } public bool Add(HallInfo hi) { return hiDAL.Insert(hi)>0; } public bool Edit(HallInfo hi) { return hiDAL.Update(hi)>0; } public bool Remove(int id) { return hiDAL.Delete(id)>0; } } } <file_sep>/CaterBLL/TableInfoBLL.cs using CaterDAL; using CaterModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CaterBLL { public partial class TableInfoBLL { private TableInfoDAL tiDAL = new TableInfoDAL(); public List<TableInfo> GetList(Dictionary<string,string> dic) { return tiDAL.GetList(dic); } public bool Add(TableInfo ti) { return tiDAL.Insert(ti)>0; } public bool Remove(int id) { return tiDAL.Delete(id) > 0; } public bool Edit(TableInfo ti) { return tiDAL.Update(ti)>0; } } } <file_sep>/CaterDAL/HallInfoDAL.cs using CaterModel; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; namespace CaterDAL { public partial class HallInfoDAL { public List<HallInfo> GetList() { List<HallInfo> list = new List<HallInfo>(); string sql = "select HId,HTitle from HallInfo where HIsDelete=0"; DataTable dt = SqlHelper.GetDataTable(sql); foreach (DataRow row in dt.Rows) { list.Add(new HallInfo() { HId = Convert.ToInt32(row[0]), HTitle=row[1].ToString() }); } return list; } public int Insert(HallInfo hi) { string sql = "insert into HallInfo(HTitle,HIsDelete) values (@title,0)"; SqlParameter p = new SqlParameter("@title",hi.HTitle); return SqlHelper.ExecuteNonQuery(sql,p); } public int Update(HallInfo hi) { string sql = "update HallInfo set HTitle=@title where Hid=@id"; SqlParameter[] p = { new SqlParameter("@title",hi.HTitle), new SqlParameter("@id",hi.HId) }; return SqlHelper.ExecuteNonQuery(sql,p); } public int Delete(int id) { string sql = "update HallInfo set HIsDelete=1 where Hid=@id"; SqlParameter p = new SqlParameter("@id",id); return SqlHelper.ExecuteNonQuery(sql,p); } } } <file_sep>/CaterUI/FrmManagerInfo.cs using CaterBll; using CaterModel; using System; using System.Linq; using System.Windows.Forms; namespace CaterUI { public partial class FrmManagerInfo : Form { private FrmManagerInfo() { InitializeComponent(); } //实现窗体的单例 private static FrmManagerInfo _form; public static FrmManagerInfo Create() { if (_form==null) { _form = new FrmManagerInfo(); } return _form; } //创建业务逻辑层对象 ManagerInfoBll miBll = new ManagerInfoBll(); private void FrmManagerInfo_Load(object sender, EventArgs e) { LoadList(); } /// <summary> /// 加载列表 /// </summary> private void LoadList() { //禁用列表的自动生成 dgvList.AutoGenerateColumns = false; //调用方法获取数据,绑定到列表的数据源上 dgvList.DataSource = miBll.GetList(); } /// <summary> /// 取消 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCancel_Click(object sender, EventArgs e) { txtId.Text = "添加时无编号"; txtName.Clear(); txtPwd.Clear(); rb0.Checked = true; btnSave.Text = "添加"; } /// <summary> /// 格式化管理员类型列 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void dgvList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { //对类型列进行格式化处理 if (e.ColumnIndex == 2) { //根据类型判断内容 e.Value = Convert.ToInt32(e.Value) == 1 ? "经理" : "店员"; } } private void dgvList_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e) { //根据当前点击的单元格,找到行与列,进行赋值 //根据索引找到行 DataGridViewRow row = dgvList.Rows[e.RowIndex]; //找到对应的列 txtId.Text = row.Cells[0].Value.ToString(); txtName.Text = row.Cells[1].Value.ToString(); if (row.Cells[2].Value.ToString().Equals("1")) { rb1.Checked = true; //值为1,则经理选中 } else { rb0.Checked = true;//如果为0,则店员选中 } //指定密码的值 txtPwd.Text = "<PASSWORD>"; btnSave.Text = "修改"; } private void btnRemove_Click(object sender, EventArgs e) { //获取选中的行 var rows = dgvList.SelectedRows; if (rows.Count > 0) { //删除前的确认提示 DialogResult result = MessageBox.Show("确定要删除吗?", "提示", MessageBoxButtons.OKCancel); if (result == DialogResult.Cancel) { //用户取消删除 return; } //获取选中行的编号 int id = int.Parse(rows[0].Cells[0].Value.ToString()); //调用删除的操作 if (miBll.Remove(id)) { //删除成功,重新加载数据 LoadList(); } } else { MessageBox.Show("请先选择要删除的行"); } } private void FrmManagerInfo_FormClosing(object sender, FormClosingEventArgs e) { //与单例保持一致 //出现这种代码的原因:Form的close()会释放当前窗体对象 _form = null; } private void btnSave_Click(object sender, EventArgs e) { //接受用户输入 ManagerInfo mi = new ManagerInfo() { MName = txtName.Text.Trim(), MPwd = txtPwd.Text.Trim(), MType = rb1.Checked ? 1 : 0 //经理值为1,店员值为0 }; if (txtId.Text.Equals("添加时无编号")) { #region 添加 //调用bll的Add方法 if (miBll.Add(mi)) { //如果添加成功,则重新加载数据 LoadList(); } else { MessageBox.Show("添加失败,请稍候重试"); } #endregion } else { #region 修改 mi.MId = int.Parse(txtId.Text); if (miBll.Edit(mi)) { LoadList(); } #endregion } //清除文本框中的值 txtName.Clear(); txtPwd.Clear(); rb0.Checked = true; btnSave.Text = "添加"; txtId.Text = "添加时无编号"; } } } <file_sep>/CaterBLL/OrderInfoBLL.cs using CaterDAL; using CaterModel; using System.Collections.Generic; namespace CaterBLL { public partial class OrderInfoBLL { private OrderInfoDAL oiDAL = new OrderInfoDAL(); public int OpenOrder(int tableId) { return oiDAL.OpenOrder(tableId); } /// <summary> /// 点菜 /// </summary> /// <param name="orderId"></param> /// <param name="dishId"></param> /// <returns></returns> public bool OrderDishes(int orderId, int dishId) { return oiDAL.OrderDishes(orderId,dishId)>0; } public List<OrderDetailInfo> GetDetailList(int orderId) { return oiDAL.GetDetailList(orderId); } public int GetOrderIdByTableId(int tableId) { return oiDAL.GetOrderIdByTableId(tableId); } public bool UpdateCountByOid(int oid, int count) { return oiDAL.UpdateCountByOid(oid,count) > 0; } public decimal GetTotalMoneyByOrderId(int orderId) { return oiDAL.GetTotalMoneyByOrderId(orderId); } public bool SetOrderMoney(int orderId,decimal money) { return oiDAL.SetOrderMomey(orderId,money)>0; } public bool DeleteDetailById(int oid) { return oiDAL.DeleteDetailById(oid)>0; } public bool Pay(bool isUserBalance, int memberId, decimal payMoney, int orderId, decimal discount) { return oiDAL.Pay(isUserBalance,memberId,payMoney,orderId,discount) >0; } } } <file_sep>/CaterBLL/DishInfoBLL.cs using CaterDAL; using CaterModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CaterBLL { public partial class DishInfoBLL { private DishInfoDAL diDAL = new DishInfoDAL(); public List<DishInfo> GetList(Dictionary<string, string> dic) { return diDAL.GetList(dic); } public bool Add(DishInfo di) { return diDAL.Insert(di) > 0; } public bool Edit(DishInfo di) { return diDAL.Update(di) > 0; } public bool Remove(int id) { return diDAL.Delete(id) > 0; } } } <file_sep>/CaterDAL/MemberInfoDAL.cs using CaterModel; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CaterDAL { public partial class MemberInfoDAL { public List<MemberInfo> GetList(Dictionary<string, string> dic) { string sql = @"select mi.*,mti.mTitle as MTypeTitle,mti.MDisCount from MemberInfo as mi inner join MemberTypeInfo as mti on mi.mTypeId=mti.mid where mi.misdelete=0"; //拼接 +and mname like '%ssdd%'"; //拼接条件 //因为要在GridView中显示会员类型的名字,而不是会员类型编号。 所以要用连接查询, //从两张表里取数据 。 会员表 会员类型表 。把两个类型一一对应起来 if (dic.Count > 0) { foreach (var pair in dic) { sql += " and mi." + pair.Key + " like '%" + pair.Value + "%'"; } } DataTable dt = SqlHelper.GetDataTable(sql); List<MemberInfo> list = new List<MemberInfo>(); foreach (DataRow row in dt.Rows) { list.Add(new MemberInfo() { MId = Convert.ToInt32(row["mid"]), MName = row["mname"].ToString(), MPhone = row["mphone"].ToString(), MMoney = Convert.ToDecimal(row["mmoney"]), MTypeId = Convert.ToInt32(row["mtypeid"]), MTypeTitle = row["mtypetitle"].ToString(), MDisCount = Convert.ToDecimal(row["MDisCount"]) }); } return list; } public int Insert(MemberInfo mi) { string sql = @"insert into MemberInfo(mtypeid,mname,mphone,mmoney,misdelete) values(@tid,@name,@phone,@money,0)"; //为SQL语句构造参数 SqlParameter[] sp = { new SqlParameter("@tid",mi.MTypeId), new SqlParameter("@name",mi.MName), new SqlParameter("@phone",mi.MPhone), new SqlParameter("@money",mi.MMoney) }; return SqlHelper.ExecuteNonQuery(sql, sp); } public int Update(MemberInfo mi) { string sql = @"update memberinfo set mname=@name,mphone=@phone,mmoney=@money,mtypeid=@tid where mid=@id"; //为语句提供参数 SqlParameter[] sp = { new SqlParameter("@name",mi.MName), new SqlParameter("@phone",mi.MPhone), new SqlParameter("@money",mi.MMoney), new SqlParameter("@tid",mi.MTypeId), new SqlParameter("@id",mi.MId) }; return SqlHelper.ExecuteNonQuery(sql,sp); } public int Delete(int id) { string sql = "update MemberInfo set mIsDelete=1 where mid=@id"; SqlParameter sp = new SqlParameter("@id", id); return SqlHelper.ExecuteNonQuery(sql, sp); } } } <file_sep>/CaterModel/DishInfo.cs using System; namespace CaterModel { public partial class DishInfo { /// <summary> /// DId /// </summary> public int DId { get; set; } /// <summary> /// DTitle /// </summary> public string DTitle { get; set; } /// <summary> /// DPrice /// </summary> public decimal DPrice { get; set; } /// <summary> /// DChar /// </summary> public string DChar { get; set; } /// <summary> /// DTypeId /// </summary> public int DTypeId { get; set; } /// <summary> /// DIsDelete /// </summary> public bool DIsDelete { get; set; } } } <file_sep>/CaterBLL/DishTypeInfoBLL.cs using CaterDAL; using CaterModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CaterBLL { public partial class DishTypeInfoBLL { private DishTypeInfoDAL dtiDAL = new DishTypeInfoDAL(); public List<DishTypeInfo> GetList() { return dtiDAL.GetList(); } public bool Add(DishTypeInfo dti) { return dtiDAL.Insert(dti)>0; } public bool Edit(DishTypeInfo dti) { return dtiDAL.Update(dti)>0; } public bool Remove(int id) { return dtiDAL.Delete(id)>0; } } } <file_sep>/CaterModel/OrderInfo.cs using System; namespace CaterModel { public class OrderInfo { /// <summary> /// OId /// </summary> public int OId { get; set; } /// <summary> /// MemberId /// </summary> public int MemberId { get; set; } /// <summary> /// TableId /// </summary> public int TableId { get; set; } /// <summary> /// ODate /// </summary> public DateTime ODate { get; set; } /// <summary> /// OMoney /// </summary> public decimal OMoney { get; set; } /// <summary> /// IsPay /// </summary> public bool IsPay { get; set; } /// <summary> /// Discount /// </summary> public decimal Discount { get; set; } } }
b8cf28c7859643481daf12bc6c49878f82a71787
[ "C#" ]
39
C#
hongjiapeng/CaterManagement
0305a7a100d1cfdadd365bf8668bf5ac41d6f073
4183d3115d5916de793731b30b4013e693e4352e
refs/heads/master
<file_sep>import React from 'react'; import {render} from 'react-dom'; import ResistanceCalculator from './assets/javascripts/ResistanceCalculator.jsx'; render(<ResistanceCalculator/>, document.getElementById('container'));
3b10a04d491b93e2d35cdadf9122be2ae54dedb1
[ "JavaScript" ]
1
JavaScript
hirosige/reactjs_template
3ddb1c4c4822ae79c4d3f3dfe541676c58a37501
21a63b3b56d125f2467d0ea89a754b7b05e86be0
refs/heads/master
<repo_name>RommelMC/courses<file_sep>/apps/courselist/models.py from __future__ import unicode_literals from django.db import models # Create your models here. class Course(models.Model): name=models.CharField(max_length=255) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) class Description(models.Model): content=models.TextField() created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) course=models.OneToOneField( Course, on_delete=models.CASCADE ) class Comment(models.Model): content=models.TextField() created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) course=models.ForeignKey(Course, related_name='comments')<file_sep>/apps/courselist/urls.py from django.conf.urls import url from . import views urlpatterns=[ url(r'^$', views.index, name='index'), url(r'^courses/destroy/(?P<id>[0-9]+)$', views.destroy, name='destroy'), url(r'^courses/delete/(?P<id>[0-9]+)$', views.delete, name='delete'), url(r'^courses/comments/(?P<id>[0-9]+)$', views.comment, name='comment'), url(r'^courses/addcomment/(?P<id>[0-9]+)$', views.addcomment, name='addcomment'), url(r'^courses/add', views.add, name='add'), ] <file_sep>/apps/courselist/views.py from django.shortcuts import render, redirect from models import * from django.core.urlresolvers import reverse # Create your views here. def index(request): context={ 'courses': Course.objects.all() } print Course.objects.all() return render(request, 'courselist/index.html', context) def destroy(request, id): context={ 'course': Course.objects.get(id=id) } return render(request, 'courselist/destroy.html', context) def delete(request, id): Course.objects.get(id=id).delete() return redirect(reverse('index')) def add(request): if request.method=='POST': course = Course.objects.create(name=request.POST['name']) Description.objects.create(content=request.POST['desc'], course=course) return redirect(reverse('index')) def comment(request, id): context={ 'comments': Course.objects.get(id=id).comments.all(), 'course':Course.objects.get(id=id) } return render(request, 'courselist/comments.html', context) def addcomment(request, id): if request.method=='POST': Comment.objects.create(content=request.POST['comment'], course=Course.objects.get(id=id)) return redirect(reverse('comment', kwargs={'id':id}))
7765bb945f1c1b8fb81c197e5f1bf39d1a25ec5f
[ "Python" ]
3
Python
RommelMC/courses
6e5cff210aeada1c8e2e94b221ee9316e4ae6c4b
bc378c58b80e191ed597d6909630feac92a00e47
refs/heads/master
<file_sep>// // DetailViewController.swift // Abyss // // Created by <NAME> on 3/18/19. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var detailDescriptionLabel: UILabel! @IBOutlet weak var profilePic: UIImageView! @IBOutlet weak var titleLbl: UILabel! @IBOutlet weak var yearLbl: UILabel! @IBOutlet weak var formatLbl: UILabel! @IBOutlet weak var episodeLbl: UILabel! @IBOutlet weak var networkLbl: UILabel! @IBOutlet weak var summaryLbl: UILabel! @IBOutlet weak var descriptionLbl: UILabel! func configureView() { if let detail = detailItem { if let label = detailDescriptionLabel { label.text = detail.name } if let label = titleLbl { label.text = detail.name } if let label = descriptionLbl { label.text = detail.description } //titleLbl.text = detail.name //title = detail.name if let label = yearLbl { if let ended = detail.yearEnd { label.text = "\(detail.yearStart) - \(ended)" } else { label.text = detail.yearStart } } if let label = formatLbl { label.text = detail.format } if let label = episodeLbl { if let countEpisodes = detail.episodes { if countEpisodes > 1 { label.text = "\(countEpisodes) Episodes" } else { label.text = "\(countEpisodes) Episodes" } } else { label.text = "" } } if let label = networkLbl { if let network = detail.network { label.text = network } else if let studio = detail.studio { label.text = studio } } if let imageView = profilePic { let url = URL(string: detail.imageURL) let data = try? Data(contentsOf: url!) imageView.image = UIImage(data: data!) } if let label = summaryLbl { label.text = detail.summary } } //titleLbl.text = detailItem?.name // Update the user interface for the detail item. /*if let detail = detailItem { if let label = detailDescriptionLabel { label.text = detail.description } }*/ } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. configureView() } var detailItem: Entry? { didSet { // Update the view. configureView() } } } <file_sep>// // DataManager.swift // Abyss // // Created by <NAME> on 3/18/19. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit class DataManager: NSObject { let MYJSONURL = "https://api.myjson.com/bins/1e5uji" var dataModel: MovieDataModel? func getData(completion: @escaping (_ dataModel: MovieDataModel) -> ()) { // let urlString = "https://api.myjson.com/bins/cgiym" let actualURL = URL(string: MYJSONURL) let dataTask = URLSession.shared.dataTask(with: actualURL!) {(data, response, error) in guard let data = data else { return } print(data.description) do { let decoder = JSONDecoder() let mediaData = try decoder.decode(MovieDataModel.self, from: data) self.dataModel = mediaData // print(self.dataModel) } catch { print("We have error") } DispatchQueue.main.async { completion(self.dataModel!) } } dataTask.resume() //let session = URLSession.shared /* let task = session.dataTask(with: actualURL!) { (data, response, error) in if let _ = data, error == nil { if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary { if let veggieArray = jsonObj!.value(forKey: "entries") as? Array<String> { self.dataArray = veggieArray } print(jsonObj!.value(forKey: "entries")!) } } else { success = false } completion(success) }*/ //task.resume() } }
753803f9751e0f6d3c849f1cb0121b736092de00
[ "Swift" ]
2
Swift
ZaneBurton/Abyss
8d1b1b2b7799dc77c7fa52b7369534071b950c48
18464d1e4563a0794c392c44672a85f2c7d37522
refs/heads/master
<repo_name>ParaschivGeorge/NestJS-Task-Manager<file_sep>/src/tasks/tasks.controller.ts import { Body, Controller, Delete, Get, Param, ParseIntPipe, Patch, Post, Query, UseGuards, UsePipes, ValidationPipe } from '@nestjs/common'; import {TasksService} from "./tasks.service"; import {CreateTaskDto} from "./dto/create-task.dto"; import {GetTaskFilterDto} from "./dto/get-task-filter.dto"; import {TaskStatusValidationPipe} from "./pipes/task-status-validation.pipe"; import {Task} from "./task.entity"; import {TaskStatus} from "./taskStatus.enum"; import {AuthGuard} from "@nestjs/passport"; import {User} from "../auth/user.entity"; import {GetUser} from "../auth/get-user.decorator"; @Controller('tasks') @UseGuards(AuthGuard()) export class TasksController { constructor(private tasksService: TasksService) { } @Get() @UsePipes(ValidationPipe) getTasks(@Query() filterDto: GetTaskFilterDto, @GetUser() user: User): Promise<Task[]> { return this.tasksService.getTasks(filterDto, user); } @Post() @UsePipes(ValidationPipe) createTask(@Body() createTaskDto: CreateTaskDto, @GetUser() user: User): Promise<Task> { return this.tasksService.createTask(createTaskDto, user); } @Get(':id') getTaskById(@Param('id', ParseIntPipe) id: number): Promise<Task> { return this.tasksService.getTaskById(id); } @Delete(':id') deleteTaskById(@Param('id', ParseIntPipe) id: number): Promise<void> { return this.tasksService.deleteTaskById(id); } @Patch(':id/status') updateTaskStatusById(@Param('id', ParseIntPipe) id: number, @Body('status', TaskStatusValidationPipe) status: TaskStatus, @GetUser() user: User): Promise<Task> { return this.tasksService.updateTaskStatusById(id, status, user); } }
00bfe867708fe9e4c12816f016a5406441818faa
[ "TypeScript" ]
1
TypeScript
ParaschivGeorge/NestJS-Task-Manager
cf74a7a74f57e26e1c8503ace2a7eb6fcfc93948
881b2c89748e36125abb8db8741dc5ebd0bf058b
refs/heads/master
<file_sep><?php $str = ''; $java = `which java`; $java = 'java'; $dir = realpath('./'); $jslint = $dir.'/lib/jslint/jslint-console.js'; $fulljslint = $dir.'/lib/jslint/fulljslint.js'; $rhino = $dir.'/lib/rhino/js.jar'; if ($_POST['source']) { $str = $_POST['source']; $tempName = tempnam(sys_get_temp_dir(), 'jslint-'); file_put_contents($tempName, stripslashes($str)); } if ($tempName) { $cmd = $java.' -jar '.escapeshellarg($rhino).' '.escapeshellarg($jslint).' '.escapeshellarg($fulljslint).' '.escapeshellarg($tempName).' 2>&1'; //This redirects error and out to out so we get it.. $out = exec($cmd); echo($out); unlink($tempName); } else { $json = new stdclass(); $json->status = 'ERROR'; $json->errors = Array('No javascript to lint.'); echo(json_encode($json)); } ?>
8c7917e38dd3bad9ebf65be5874e7695af35cbff
[ "PHP" ]
1
PHP
davglass/jslint-service
dc1a277efe972a69e192882fe3d601f33966e3c1
4272618634a6b8d019096590acbb7c1e7204b907
refs/heads/master
<repo_name>Xaambo/calculadoraDivisasJava<file_sep>/settings.gradle include ':app' rootProject.name='calculadoraDivisasJava' <file_sep>/app/src/main/java/com/example/calculadoradivisasjava/MainActivity.java package com.example.calculadoradivisasjava; import androidx.appcompat.app.AppCompatActivity; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.math.BigDecimal; import java.math.RoundingMode; public class MainActivity extends AppCompatActivity { Conversor conversor = new Conversor(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn1 = findViewById(R.id.btn1); Button btn2 = findViewById(R.id.btn2); Button btn3 = findViewById(R.id.btn3); Button btn4 = findViewById(R.id.btn4); Button btn5 = findViewById(R.id.btn5); Button btn6 = findViewById(R.id.btn6); Button btn7 = findViewById(R.id.btn7); Button btn8 = findViewById(R.id.btn8); Button btn9 = findViewById(R.id.btn9); Button btn0 = findViewById(R.id.btn0); Button btnComa = findViewById(R.id.btnComa); Button btnIgual = findViewById(R.id.btnIgual); Button btnCE = findViewById(R.id.btnCE); Button btnDEL = findViewById(R.id.btnDEL); final Button btnLibra = findViewById(R.id.btnLibra); final Button btnYen = findViewById(R.id.btnYen); final Button btnDollar = findViewById(R.id.btnDollar); final Button btnYuan = findViewById(R.id.btnYuan); final TextView tvIn = findViewById(R.id.tvIn); final TextView tvOut = findViewById(R.id.tvOut); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addnumero(1, tvIn); } }); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addnumero(2, tvIn); } }); btn3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addnumero(3, tvIn); } }); btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addnumero(4, tvIn); } }); btn5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addnumero(5, tvIn); } }); btn6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addnumero(6, tvIn); } }); btn7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addnumero(7, tvIn); } }); btn8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addnumero(8, tvIn); } }); btn9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addnumero(9, tvIn); } }); btn0.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addnumero(0, tvIn); } }); btnComa.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addcoma(',', tvIn); } }); btnCE.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { netejarPantalla(tvIn, tvOut); } }); btnDEL.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { eliminarNumero(tvIn); } }); btnIgual.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { operacio(tvIn, tvOut, conversor); } }); btnDollar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { conversor = fctConversio((String)btnDollar.getText(), conversor, btnDollar, tvIn, tvOut); } }); btnLibra.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { conversor = fctConversio((String)btnLibra.getText(), conversor, btnLibra, tvIn, tvOut); } }); btnYen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { conversor = fctConversio((String)btnYen.getText(), conversor, btnYen, tvIn, tvOut); } }); btnYuan.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { conversor = fctConversio((String)btnYuan.getText(), conversor, btnYuan, tvIn, tvOut); } }); } private void addnumero(int num, TextView tvIn) { String tvContent; String actualString; int actualInt; float actualFloat; int index; tvContent = tvIn.getText().toString(); if (tvContent.length() < 7) { if (!tvContent.contains(",")) { actualInt = Integer.parseInt(tvContent); if (actualInt == 0) { tvIn.setText(""); tvContent = String.valueOf(actualInt + num); tvIn.setText(tvContent); } else { tvContent = String.valueOf(num); tvContent = String.valueOf(actualInt + tvContent); tvIn.setText(tvContent); } } else { if (tvContent.charAt(tvContent.length() - 1) == ',') { tvContent = tvContent.substring(0, (tvContent.length() - 1)); actualFloat = Float.parseFloat(tvContent); actualString = String.valueOf(actualFloat); actualString = actualString.substring(0, (actualString.length() - 2)) + ","; } else { actualString = tvContent; } index = actualString.indexOf(","); if ((tvContent.length() - 3) != index) { tvContent = String.valueOf(num); tvContent = String.valueOf(actualString + tvContent); tvIn.setText((tvContent)); } } } } private void addcoma(char coma, TextView tvIn) { String tvContent; tvContent = tvIn.getText().toString(); if (!tvContent.contains(",")) { tvContent = tvContent + coma; tvIn.setText(tvContent); } else { tvIn.setText(tvContent); } } private void operacio(TextView tvIn, TextView tvOut, Conversor conversor) { float fctConversio; float inFloat; float outFloat; String outText; String inText; fctConversio = conversor.getConversio(); inText = tvIn.getText().toString(); inText = inText.replace(',','.'); inFloat = Float.parseFloat(inText); outFloat = inFloat*fctConversio; outText = String.valueOf(outFloat); outText = truncate(outText, 2); outText = outText.replace('.',','); tvOut.setText(outText); } private String truncate(String value, int places) { return new BigDecimal(value).setScale(places, RoundingMode.DOWN).stripTrailingZeros().toString(); } private Conversor fctConversio(String moneda, Conversor conversor, Button btnClicked, TextView tvIn, TextView tvOut) { String ultimaMoneda; ultimaMoneda = conversor.getUltimaMoneda(); if (!ultimaMoneda.equals(moneda)) { dialogConEditText(moneda, conversor, btnClicked); tvIn.setText("0"); tvOut.setText("0"); } return conversor; } private void dialogConEditText(final String moneda, final Conversor conversor, final Button btnClicked) { AlertDialog ad; ad = new AlertDialog.Builder(this).create(); ad.setTitle("Factor de conversió"); ad.setMessage("Quin es el factor de conversió del " + moneda); // Ahora forzamos que aparezca el editText final EditText edtValor = new EditText(this); ad.setView(edtValor); ad.setButton(AlertDialog.BUTTON_POSITIVE,"Aceptar", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String conversio; float conversioF; Button ultimaMoneda; ultimaMoneda = conversor.getBtn(); conversio = edtValor.getText().toString(); conversioF = Float.parseFloat(conversio); if (ultimaMoneda != null) { ultimaMoneda.setBackgroundColor(Color.parseColor("#ABABAB")); } conversor.setConversio(conversioF); conversor.setUltimaMoneda(moneda); conversor.setBtn(btnClicked); btnClicked.setBackgroundColor(Color.parseColor("#000000")); } }); ad.show(); // el Show es asíncrono. } private void eliminarNumero(TextView tvIn) { String text = (String) tvIn.getText(); String newText; if (text.length() > 1) { newText = text.substring(0, (text.length() - 1)); tvIn.setText(newText); } else { tvIn.setText("0"); } } private void netejarPantalla(TextView tvIn, TextView tvOut) { tvIn.setText("0"); tvOut.setText("0"); } }
4b84eef53e55dd609ac2ea7339adeb62a1ba5913
[ "Java", "Gradle" ]
2
Gradle
Xaambo/calculadoraDivisasJava
a69215f6c3bb7a4c3024082eb13a570bad1e4326
8bb73faebfb871f7103465de038e40fea9b4bb6a
refs/heads/master
<repo_name>rpydaneogrendim/gsmoperatorleri_sikayetvar<file_sep>/gsmoperatorleri_sikayetvar.R library(tidyverse);library(rvest);library(stringr) url_tt <- "https://www.sikayetvar.com/turk-telekom" url_tt_ek <- "?page=" tt_links <- str_c(url_tt,url_tt_ek,seq(2,1000,1)) #1000 sayfa tt_links <- c(url_tt,tt_links) basliklari_cek <- function(master_df){ as.data.frame( read_html(master_df) %>% html_nodes(".complaint-link-for-ads") %>% html_text() ) } basliklar_tt <- tt_links %>% map(basliklari_cek) %>% bind_rows() colnames(basliklar_tt) <- "text" ####################################################### url_tcell <- "https://www.sikayetvar.com/turkcell" url_tcell_ek <- "?page=" tcell_links <- str_c(url_tcell,url_tcell_ek,seq(2,1000,1)) #1000 sayfa tcell_links <- c(url_tcell,tcell_links) # basliklari_cek <- function(master_df){ # as.data.frame( # read_html(master_df) %>% # html_nodes(".complaint-link-for-ads") %>% # html_text() # ) # } basliklar_tcell <- tcell_links %>% map(basliklari_cek) %>% bind_rows() colnames(basliklar_tcell) <- "text" ####################################################### url_voda <- "https://www.sikayetvar.com/vodafone" url_voda_ek <- "?page=" voda_links <- str_c(url_voda,url_voda_ek,seq(2,1000,1)) #1000 sayfa voda_links <- c(url_voda,voda_links) # basliklari_cek <- function(master_df){ # as.data.frame( # read_html(master_df) %>% # html_nodes(".complaint-link-for-ads") %>% # html_text() # ) # } basliklar_voda <- voda_links %>% map(basliklari_cek) %>% bind_rows() colnames(basliklar_voda) <- "text" ####################################################### basliklar_tt$operator <- "turktelekom" basliklar_tcell$operator <- "turkcell" basliklar_voda$operator <- "vodafone" gsmoperatorleri_final <- rbind(basliklar_tt, basliklar_tcell, basliklar_voda) ####################################################### write.csv(x = gsmoperatorleri_final, file = "gsmoperatorleri_final.csv", row.names = FALSE) write.table(x = gsmoperatorleri_final, file = "gsmoperatorleri_final.txt", row.names = FALSE) #Her bir gsm operatörü için 1000 sayfaya kadar şikayet başlıkları alındı. #Excel dosyasındaki boşluklar 'önceki şikayet', 'sonraki şikayet' satırlarıdır; kaldırılabilir. #Alternatif olarak text dosyası da kullanılabilir. #Web kazıma güncel tarihi: 2019-09-29 #Site: https://www.sikayetvar.com/
78dea071388c861571524ff875f3de4cb21fb225
[ "R" ]
1
R
rpydaneogrendim/gsmoperatorleri_sikayetvar
a4d9bdfd4fd8b6a4c6f2565fe2a802f38ab3284f
11df128cf01ed9a7975f8847d90cf2cf9c830045
refs/heads/master
<repo_name>asniii/simple-aws-sns-http-endpoint<file_sep>/README.md # simple-aws-sns-http-endpoint This is a amazon sns http endpoint. Add this endpoint as a subcriber to the sns topic. The endpoint path is : http://address:8080/simple-aws-sns-http-endpoint/webapi/myresource/snsmessage <file_sep>/src/main/java/com/example/MyResource.java package com.example; import com.example.sns.SnsConfirmationRequest; import com.example.sns.SnsMsg; import com.example.sns.SnsNotificationMsg; import com.example.sns.SnsUtils; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; /** * Root resource (exposed at "myresource" path) */ @Path("/myresource") public class MyResource { /** * This is the sns-endpoint. You sns should hit this endpoint. */ @Path("/snsmessage/") @POST @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) public String snsEndPoint(String snsRequest, @Context HttpHeaders headers) { //First we will check from where we have invoked this http endpoint. String messageType = headers.getHeaderString("x-amz-sns-message-type"); if (messageType == null) { System.out.println("This is not hit by sns."); return "Plz hit this endpoint from amazon simple notification service."; } else { SnsMsg snsMsg; switch (messageType) { case "SubscriptionConfirmation": snsMsg = SnsUtils.create(snsRequest, SnsConfirmationRequest.class); break; case "Notification": snsMsg = SnsUtils.create(snsRequest, SnsNotificationMsg.class); break; default: System.out.println("Unsupported SNS message type: " + messageType); throw new BadRequestException(); } // This is basically checking the request message is correct or not. // The signature is based on SignatureVersion 1. // If the sig version is something other than 1, // throw an exception. if (snsMsg.getSignatureVersion().equals("1")) { // Check the signature and throw an exception if the signature verification fails. if (SnsUtils.isMessageSignatureValid(snsMsg)) { System.out.println(">>Signature verification succeeded"); } else { System.out.println(">>Signature verification failed"); throw new SecurityException("Signature verification failed."); } } else { System.out.println(">>Unexpected signature version. Unable to verify signature."); throw new SecurityException("Unexpected signature version. Unable to verify signature."); } //Now handling the message switch (messageType) { //If it is a subscription confirmation request message. Then we hit back at the confirmation URL. case "SubscriptionConfirmation": SnsUtils.confirmSubscription((SnsConfirmationRequest) snsMsg); System.out.println("Subscribed to sns topic."); break; case "Notification": System.out.println("If u are getting this message at catalina.out. Then everything works fine. Work done."); System.out.println("message:: " + snsMsg.getMessage()); } } return "Got it!"; } } <file_sep>/src/main/java/com/example/sns/SnsConfirmationRequest.java package com.example.sns; import com.fasterxml.jackson.annotation.JsonProperty; public class SnsConfirmationRequest extends SnsMsg { private String token; private String subscribeURL; @JsonProperty("Token") public String getToken() { return token; } public void setToken(String token) { this.token = token; } @JsonProperty("SubscribeURL") public String getSubscribeURL() { return subscribeURL; } public void setSubscribeURL(String subscribeURL) { this.subscribeURL = subscribeURL; } }
8a17397afba240fff039f881bbe0c4d99eb83464
[ "Markdown", "Java" ]
3
Markdown
asniii/simple-aws-sns-http-endpoint
dfa144f10131231f04608c63e97014902a54601f
1f7f2734ccaee822520a27d98c5ba980257916c0
refs/heads/main
<file_sep>#include <iostream> using namespace std; struct Linkedlist { const char* data; Linkedlist* next; Linkedlist(const char* string) { data = string; this->next = NULL; } ~Linkedlist() { delete[]data; delete[]next; } Linkedlist* addFirst(const char* c) { Linkedlist* tmp = new Linkedlist(c); tmp->next = this; return tmp; } void addLast(const char* c) { Linkedlist* tmp = new Linkedlist(c); Linkedlist* read = this; while (read->next != NULL) read = read->next; read->next = tmp; } void print() { Linkedlist* read = this; while (read != NULL) { cout << read->data << " "; read = read->next; } cout << "\n--------------\n"; } Linkedlist* removeFirst() { return this->next; } void removeLast() { Linkedlist* read = this; while (read->next->next != NULL) read = read->next; read->next = NULL; } void insertAfter(Linkedlist* p, const char* c) { Linkedlist* tmp = new Linkedlist(c); if (p->next == NULL) p->next = tmp; else { tmp->next = p->next; p->next = tmp; } } Linkedlist* removeNode(Linkedlist* p) { if (this == p) return this->next; else if (p->next == NULL) { removeLast(); return this; } else { Linkedlist* read = this; while (read->next != p) read = read->next; read->next = p->next; return this; } } }; int main() { Linkedlist* f = new Linkedlist("Heavy"); f = f->addFirst("Metal"); f->addLast("Burst"); f->print(); f = f->removeFirst(); f->print(); f->removeLast(); f->print(); f->insertAfter(f, "Lina"); f->print(); f->insertAfter(f, "K"); f = f->removeNode(f->next); f->print(); return 0; }
d8ab5fb8e996abfb2354dcc345c525deee435097
[ "C++" ]
1
C++
Yami-Karen/Week13_-12-
82d3eff93964bbe6f89273fc65162228c6fd0411
e4c3c9def75bcc4380ae7f6eef84922fe3cf5fea
refs/heads/master
<file_sep>/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local */ import React from 'react'; import { Platform, ScrollView, Switch, Text, SafeAreaView, View, ActivityIndicator, Modal } from 'react-native'; import { Header, LearnMoreLinks, Colors, DebugInstructions, ReloadInstructions, } from 'react-native/Libraries/NewAppScreen'; import BluetoothSerial, { withSubscription } from "react-native-bluetooth-serial-next"; import Button from "./components/Button"; import DeviceList from "./components/DeviceList"; import styles from "./styles"; const util = require('util'); class App extends React.Component { constructor(props) { super(props); this.events = null; this.state = { isEnabled: false, device: null, devices: [], scanning: false, processing: false, msg:"Sin mensaje", http: false }; } async componentDidMount() { this.events = this.props.events; try { const [isEnabled, devices] = await Promise.all([ BluetoothSerial.isEnabled(), BluetoothSerial.list() ]); this.setState({ isEnabled, devices: devices.map(device => ({ ...device, paired: true, connected: false })) }); console.log(devices); } catch (e) { console.log("sale mensaje: "); console.log(e.messaage); } this.events.on("bluetoothEnabled", () => { console.log("BT encendido!!") this.setState({ isEnabled: true }); }); this.events.on("bluetoothDisabled", () => { console.log("BT apagado!!") this.setState({ isEnabled: false }); }); this.events.on("data", result => { if (result) { const { id, data } = result; console.log(`Data from device ${id} : ${data}`); console.log("sucedio el evento data") } }); this.events.on("read", result => { if (result) { const { id, data } = result; console.log(`Data from device ${id} : ${data}`); console.log("sucedio el evento leer") } }); this.events.on("error", e => { if (e) { console.log(`Error: ${e.message}`); } }); } write = async (id, message) => { try { await BluetoothSerial.device(id).write(message); } catch (e) { } }; read = async (id) => { try { await BluetoothSerial.device(id).readEvery((data, intervalId) => { var device_ = this.state.device; if(device_){ if(String(data) != ""){ this.setState({ msg: data }) console.log("Seescribio con BT: "); console.log(this.state.msg); } } if (this.imBoredNow && intervalId) { clearInterval(intervalId); } }, 50, "#" ); } catch (e) { } }; requestEnable = () => async () => { try { await BluetoothSerial.requestEnable(); this.setState({ isEnabled: true }); } catch (e) { console.log(e.message); } }; toggleBluetooth = async value => { try { if (value) { await BluetoothSerial.enable(); this.listDevices(); } else { await BluetoothSerial.disable(); } } catch (e) { console.log("Hay un erro al encender"); } }; listDevices = async () => { try { const list = await BluetoothSerial.list(); const [isEnabled, devices] = await Promise.all([ BluetoothSerial.isEnabled(), BluetoothSerial.list() ]); this.setState({ isEnabled, devices: devices.map(device => ({ ...device, paired: true, connected: false })) }); } catch (e) { } }; discoverUnpairedDevices = async () => { this.setState({ scanning: true }); try { const unpairedDevices = await BluetoothSerial.listUnpaired(); this.setState(({ devices }) => ({ scanning: false, devices: devices .map(device => { const found = unpairedDevices.find(d => d.id === device.id); if (found) { return { ...device, ...found, connected: false, paired: false }; } return device.paired || device.connected ? device : null; }) .map(v => v) })); } catch (e) { this.setState(({ devices }) => ({ scanning: false, devices: devices.filter(device => device.paired || device.connected) })); } }; cancelDiscovery = () => async () => { try { await BluetoothSerial.cancelDiscovery(); this.setState({ scanning: false }); } catch (e) { } }; toggleDevicePairing = async ({ id, paired }) => { if (paired) { await this.unpairDevice(id); } else { await this.pairDevice(id); } }; pairDevice = async id => { this.setState({ processing: true }); try { const paired = await BluetoothSerial.pairDevice(id); if (paired) { this.setState(({ devices, device }) => ({ processing: false, device: { ...device, ...paired, paired: true }, devices: devices.map(v => { if (v.id === paired.id) { return { ...v, ...paired, paired: true }; } return v; }) })); } else { this.setState({ processing: false }); } } catch (e) { this.setState({ processing: false }); } }; unpairDevice = async id => { this.setState({ processing: true }); try { const unpaired = await BluetoothSerial.unpairDevice(id); if (unpaired) { this.setState(({ devices, device }) => ({ processing: false, device: { ...device, ...unpaired, connected: false, paired: false }, devices: devices.map(v => { if (v.id === unpaired.id) { return { ...v, ...unpaired, connected: false, paired: false }; } return v; }) })); } else { this.setState({ processing: false }); } } catch (e) { this.setState({ processing: false }); } }; toggleDeviceConnection = async ({ id, connected }) => { if (connected) { await this.disconnect(id); } else { await this.connect(id); } }; connect = async id => { this.setState({ processing: true }); try { const connected = await BluetoothSerial.device(id).connect(); if (connected) { this.setState(({ devices, device }) => ({ processing: false, device: { ...device, ...connected, connected: true }, devices: devices.map(v => { if (v.id === connected.id) { return { ...v, ...connected, connected: true }; } return v; }) })); } else { this.setState({ processing: false }); } } catch (e) { this.setState({ processing: false }); } }; disconnect = async id => { this.setState({ processing: true }); try { await BluetoothSerial.device(id).disconnect(); this.setState(({ devices, device }) => ({ processing: false, device: { ...device, connected: false }, devices: devices.map(v => { if (v.id === id) { return { ...v, connected: false }; } return v; }) })); } catch (e) { this.setState({ processing: false }); } }; ciclo(){ const that =this; function funcpromes(){ const that2=that; fetch("http://192.168.0.19:80") .then(res => res.text()) .then(data => { that2.setState({ msg:data }); console.log("enviando en http"); if(that2.state.http){ setTimeout(funcpromes, 100); } }); // console.log(that2.state.variTR) } const promes = util.promisify(funcpromes); promes() } renderModal = (device, processing) => { if (!device) return null; const { id, name, paired, connected } = device; return ( <Modal animationType="fade" transparent={false} visible={true} onRequestClose={() => {}} > {device ? ( <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }} > <Text style={{ fontSize: 18, fontWeight: "bold" }}>{name}</Text> <Text style={{ fontSize: 14 }}>{`<${id}>`}</Text> {processing && ( <ActivityIndicator style={{ marginTop: 15 }} size={Platform.OS === "ios" ? 1 : 60} /> )} {!processing && ( <View style={{ marginTop: 20, width: "50%" }}> {Platform.OS !== "ios" && ( <Button title={paired ? "Desemparejar" : "Emparejar"} style={{ backgroundColor: "#22509d" }} textStyle={{ color: "#fff" }} onPress={() => this.toggleDevicePairing(device)} /> )} <Button title={connected ? "Desconectar" : "Conectar"} style={{ backgroundColor: "#22509d" }} textStyle={{ color: "#fff" }} onPress={() => this.toggleDeviceConnection(device)} /> {connected && ( <React.Fragment> <Button title="Escribir en BT" style={{ backgroundColor: "#22509d" }} textStyle={{ color: "#fff" }} onPress={() => this.write( id, "This is the test message\r\nDoes it work?\r\nTell me it works!\r\n" ) } /> <Button title="Leer de BT" style={{ backgroundColor: "#22509d" }} textStyle={{ color: "#fff" }} onPress={() => this.read(id) } /> <View style={{ top: 30, //flex: 1, alignItems: "center", justifyContent: "center", //backgroundColor: "#74F39E", borderRadius:10, borderWidth:3, borderColor: "#22509d", height: 170, width: "100%" }}> <Text style={{ top: 10, fontSize: 24, fontWeight: "bold"}} >Mensaje recibido</Text> <Text style={{ top: 20, fontSize: 40, fontWeight: "bold", color: "#0A92F6",}} > {this.state.msg} </Text> </View> </React.Fragment> )} <Button style={{ top:150 }} title="Atras" onPress={() => this.setState({ device: null })} /> </View> )} </View> ) : null} </Modal> ); }; renderModal2 = () => { var http_ = this.state.http; if (!http_) return null; return ( <Modal animationType="fade" transparent={false} visible={true} onRequestClose={() => {}} > {http_ ? ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center"}}> <View style={{ marginTop: 20, width: "80%"}}> <Button title="Leer servidor" style={{ backgroundColor: "#22509d" }} textStyle={{ color: "#fff" }} onPress={() => this.ciclo() } /> <View style={{ top: 30, //flex: 1, alignItems: "center", justifyContent: "center", //backgroundColor: "#74F39E", borderRadius:10, borderWidth:3, borderColor: "#22509d", height: 170, width: "100%" }}> <Text style={{ top: 10, fontSize: 24, fontWeight: "bold"}} >Mensaje recibido</Text> <Text style={{ top: 20, fontSize: 48, fontWeight: "bold", color: "#0A92F6",}} > {this.state.msg} </Text> </View> <Button style={{ top:150 }} title="Atras" onPress={() => this.setState({ http: null })}> </Button> </View> </View> ) : null} </Modal> ); }; render() { const { isEnabled, device, devices, scanning, processing } = this.state; return ( <SafeAreaView style={{ flex: 1 }}> <View style={styles.topBar}> <Text style={styles.heading}>Ejemplo Bluetooth y HTTP Request</Text> <View style={styles.enableInfoWrapper}> <Text style={{ fontSize: 11, color: "#fff", paddingRight: 10 }}> {isEnabled ? "Encendido" : "Apagado"} </Text> <Switch onValueChange={this.toggleBluetooth} value={isEnabled} /> </View> </View> {scanning ? ( isEnabled && ( <View style={{ flex: 1, alignItems: "center", justifyContent: "center" }} > <ActivityIndicator style={{ marginBottom: 15 }} size={Platform.OS === "ios" ? 1 : 60} /> <Button textStyle={{ color: "#fff" }} style={styles.buttonRaised} title="Cancelar busqueda" onPress={this.cancelDiscovery} /> </View> ) ) : ( <React.Fragment> {this.renderModal(device, processing)} <DeviceList devices={devices} onDevicePressed={device => this.setState({ device })} onRefresh={this.listDevices} /> </React.Fragment> )} <React.Fragment> {this.renderModal2()} <View style={{ bottom:250, alignItems: "center", justifyContent: "center" }}> <Button title="Conectar con servidor HTTP" style={{ backgroundColor: "#22509d" }} textStyle={{ color: "#fff" }} onPress={() => this.setState({ http: true }) } /> </View> </React.Fragment> <View style={styles.footer}> <ScrollView horizontal contentContainerStyle={styles.fixedFooter}> {isEnabled && ( <Button title="Buscar disp. BT" onPress={this.discoverUnpairedDevices} /> )} {!isEnabled && ( <Button title="Habilitar permiso de Bluetooth" onPress={this.requestEnable} /> )} </ScrollView> </View> </SafeAreaView> ); } }; export default withSubscription({ subscriptionName: "events" })(App);
91bf6e325153047169034246dd701aa9ed3dfe4a
[ "JavaScript" ]
1
JavaScript
DavidErira/App_BT_y_HTTP
1a74bb25db99211f9b5d7f2454f22720e47c0e27
88eaac8eb5b08771e6c0a4e8ea227f301f27b794
refs/heads/master
<repo_name>gregorl82/Android_Trivia_Application<file_sep>/settings.gradle rootProject.name='Qwizzr' include ':app' <file_sep>/app/src/main/java/com/example/android/qwizzr/ui/GameFragment.kt package com.example.android.qwizzr.ui import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import com.example.android.qwizzr.R import com.example.android.qwizzr.databinding.FragmentGameBinding /** * A simple [Fragment] subclass. */ class GameFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val binding = DataBindingUtil.inflate<FragmentGameBinding>( inflater, R.layout.fragment_game, container, false ) return binding.root } } <file_sep>/app/src/main/java/com/example/android/qwizzr/model/Question.kt package com.example.android.qwizzr.model data class Question ( val questionText: String, val correctAnswer: String, val incorrectAnswers: ArrayList<String> )
66e2f3e63ac0b787c7701fb07eac9f500892892d
[ "Kotlin", "Gradle" ]
3
Gradle
gregorl82/Android_Trivia_Application
f8624f6ab4154850230ee96ed072c789ed22a985
edf7db7469fc461930f325d862b7c85a67242ebb
refs/heads/master
<repo_name>sundeepkamath/PersonalBlog<file_sep>/src/Blog/gulpfile.js /// <binding BeforeBuild='min' /> /* This file in the main entry point for defining Gulp tasks and using Gulp plugins. Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007 */ var gulp = require('gulp'), concat = require('gulp-concat'), cssmin = require('gulp-cssmin'), uglify = require('gulp-uglify'); var paths = { webroot: "./wwwroot/" }; paths.styleCss = paths.webroot + "css/style.css"; paths.cssDest = paths.webroot + "css"; gulp.task('min:css', function () { // place code for your default task here return gulp.src([paths.styleCss]) .pipe(concat(paths.cssDest + "/min/style.min.css")) .pipe(cssmin()) .pipe(gulp.dest(".")); //.pipe(gulp.dest(paths.cssDest + "/min/style.min.css")); }); gulp.task("min", ["min:css"]);<file_sep>/src/Blog/Models/PostsListModel.cs using Blog.Data.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Blog.Models { public class PostsListModel { public IList<Post> Posts { get; set; } public int TotalPosts { get; set; } } } <file_sep>/src/Blog.Data/Entities/Post.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Blog.Data.Entities { public class Post { public Post() { this.PostTags = new List<PostTag>(); } public int Id { get; set; } [MaxLength(500)] [Required] public string Title { get; set; } [MaxLength(5000)] [Required] public string ShortDescription { get; set; } [MaxLength(5000)] [Required] public string Description { get; set; } [MaxLength(1000)] [Required] public string Meta { get; set; } [MaxLength(200)] [Required] public string UrlSlug { get; set; } [Required] public bool Published { get; set; } [Required] public DateTime PostedOn { get; set; } public DateTime? ModifiedOn { get; set; } public virtual Category Category { get; set; } public virtual ICollection<PostTag> PostTags { get; set; } } } <file_sep>/src/Blog.Data/Migrations/20160212154933_InitialDB.cs using System; using System.Collections.Generic; using Microsoft.Data.Entity.Migrations; using Microsoft.Data.Entity.Metadata; namespace Blog.Data.Migrations { public partial class InitialDB : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Category", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Description = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: false), UrlSlug = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Category", x => x.Id); }); migrationBuilder.CreateTable( name: "Tag", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Description = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: false), UrlSlug = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Tag", x => x.Id); }); migrationBuilder.CreateTable( name: "Post", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), CategoryId = table.Column<int>(nullable: true), Description = table.Column<string>(nullable: false), Meta = table.Column<string>(nullable: false), ModifiedOn = table.Column<DateTime>(nullable: true), PostedOn = table.Column<DateTime>(nullable: false), Published = table.Column<bool>(nullable: false), ShortDescription = table.Column<string>(nullable: false), Title = table.Column<string>(nullable: false), UrlSlug = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Post", x => x.Id); table.ForeignKey( name: "FK_Post_Category_CategoryId", column: x => x.CategoryId, principalTable: "Category", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "PostTag", columns: table => new { PostId = table.Column<int>(nullable: false), TagId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_PostTag", x => new { x.PostId, x.TagId }); table.ForeignKey( name: "FK_PostTag_Post_PostId", column: x => x.PostId, principalTable: "Post", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_PostTag_Tag_TagId", column: x => x.TagId, principalTable: "Tag", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable("PostTag"); migrationBuilder.DropTable("Post"); migrationBuilder.DropTable("Tag"); migrationBuilder.DropTable("Category"); } } } <file_sep>/src/Blog.Data/Repositories/BlogRepository.cs using Blog.Data.RepositoryInterfaces; using System; using System.Runtime; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Blog.Data.Entities; using Blog.Data.DatabaseContexts; using Microsoft.Data.Entity; namespace Blog.Data.Repositories { public class BlogRepository : IBlogRepository { private BlogContext _context; public BlogRepository(BlogContext context) { _context = context; } public IList<Post> GetPosts(int pageNumber, int pageSize) { int pagesToSkip = pageNumber == 1 ? 0 : (pageNumber > 1 ? pageNumber - 1 : 1); return _context.Posts .Where<Post>(p => p.Published) .OrderByDescending(p => p.PostedOn) .Skip(pagesToSkip * pageSize) .Take(pageSize) .Include(p => p.Category) .ToList<Post>(); } public int TotalPosts() { return _context.Posts.Where<Post>(p => p.Published).Count(); } } } <file_sep>/src/Blog/Startup.cs using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.DependencyInjection; using Blog.Data.DatabaseContexts; using Blog.Data.RepositoryInterfaces; using Blog.Data.Repositories; using Blog.Data.Extensions; using Microsoft.Data.Entity; using Microsoft.Extensions.PlatformAbstractions; using Microsoft.Extensions.Configuration; namespace Blog { public class Startup { public IConfiguration Configuration { get; set; } public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { var builder = new ConfigurationBuilder() .SetBasePath(appEnv.ApplicationBasePath) .AddJsonFile("config.json") .AddEnvironmentVariables(); Configuration = builder.Build(); } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddEntityFramework() .AddSqlServer() .AddDbContext<BlogContext>(); //(options => { // options.UseSqlServer(Configuration["Data:BlogDB"]); // }); services.AddScoped<IBlogRepository, BlogRepository>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope()) { serviceScope.ServiceProvider.GetService<BlogContext>().Database.Migrate(); serviceScope.ServiceProvider.GetService<BlogContext>().Database.EnsureCreated(); serviceScope.ServiceProvider.GetService<BlogContext>().EnsureSeedData(); } } app.UseIISPlatformHandler(); app.UseStaticFiles(); app.UseMvc(config => { config.MapRoute( name: "Default", template: "{controller}/{action}/{id?}", defaults: new { controller="Blog", action="Posts" } ); }); } // Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); } } <file_sep>/src/Blog.Data/Entities/Tag.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Blog.Data.Entities { public class Tag { public Tag() { this.PostTags = new List<PostTag>(); } public int Id { get; set; } [Required] [MaxLength(50)] public string Name { get; set; } [Required] [MaxLength(50)] public string UrlSlug { get; set; } [MaxLength(200)] public string Description { get; set; } public virtual ICollection<PostTag> PostTags { get; set; } } } <file_sep>/src/Blog/Controllers/Web/BlogController.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using Blog.Data.RepositoryInterfaces; using Blog.Models; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace Blog.Controllers.Web { public class BlogController : Controller { private IBlogRepository _repo; public BlogController(IBlogRepository repo) { _repo = repo; } // GET: /<controller>/ public ViewResult Posts(int pageNumber = 1) { var posts = _repo.GetPosts(pageNumber, 10); var totalPosts = _repo.TotalPosts(); var postsListModel = new PostsListModel { Posts = posts, TotalPosts = totalPosts }; return View(postsListModel); } } } <file_sep>/src/Blog.Data/RepositoryInterfaces/IBlogRepository.cs using Blog.Data.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Blog.Data.RepositoryInterfaces { public interface IBlogRepository { IList<Post> GetPosts(int pageNumber, int pageSize); int TotalPosts(); } } <file_sep>/src/Blog.Data/Migrations/BlogContextModelSnapshot.cs using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using Blog.Data.DatabaseContexts; namespace Blog.Data.Migrations { [DbContext(typeof(BlogContext))] partial class BlogContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Blog.Data.Entities.Category", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description") .HasAnnotation("MaxLength", 200); b.Property<string>("Name") .IsRequired() .HasAnnotation("MaxLength", 50); b.Property<string>("UrlSlug") .IsRequired() .HasAnnotation("MaxLength", 50); b.HasKey("Id"); }); modelBuilder.Entity("Blog.Data.Entities.Post", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CategoryId"); b.Property<string>("Description") .IsRequired() .HasAnnotation("MaxLength", 5000); b.Property<string>("Meta") .IsRequired() .HasAnnotation("MaxLength", 1000); b.Property<DateTime?>("ModifiedOn"); b.Property<DateTime>("PostedOn"); b.Property<bool>("Published"); b.Property<string>("ShortDescription") .IsRequired() .HasAnnotation("MaxLength", 5000); b.Property<string>("Title") .IsRequired() .HasAnnotation("MaxLength", 500); b.Property<string>("UrlSlug") .IsRequired() .HasAnnotation("MaxLength", 200); b.HasKey("Id"); }); modelBuilder.Entity("Blog.Data.Entities.PostTag", b => { b.Property<int>("PostId"); b.Property<int>("TagId"); b.HasKey("PostId", "TagId"); }); modelBuilder.Entity("Blog.Data.Entities.Tag", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Description") .HasAnnotation("MaxLength", 200); b.Property<string>("Name") .IsRequired() .HasAnnotation("MaxLength", 50); b.Property<string>("UrlSlug") .IsRequired() .HasAnnotation("MaxLength", 50); b.HasKey("Id"); }); modelBuilder.Entity("Blog.Data.Entities.Post", b => { b.HasOne("Blog.Data.Entities.Category") .WithMany() .HasForeignKey("CategoryId"); }); modelBuilder.Entity("Blog.Data.Entities.PostTag", b => { b.HasOne("Blog.Data.Entities.Post") .WithMany() .HasForeignKey("PostId"); b.HasOne("Blog.Data.Entities.Tag") .WithMany() .HasForeignKey("TagId"); }); } } } <file_sep>/src/Blog.Data/DatabaseContexts/BlogContext.cs using Microsoft.Data.Entity; using Blog.Data.Entities; namespace Blog.Data.DatabaseContexts { public class BlogContext : DbContext { public BlogContext() { } public DbSet<Post> Posts { get; set; } public DbSet<Tag> Tags { get; set; } public DbSet<Category> Categories { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var connectionString = "Server=(localdb)\\ProjectsV12;Database=BlogDB;Trusted_Connection=true;MultipleActiveResultSets=true;"; optionsBuilder.UseSqlServer(connectionString); base.OnConfiguring(optionsBuilder); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<PostTag>() .HasKey(t => new { t.PostId, t.TagId }); modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Post) .WithMany(p => p.PostTags) .HasForeignKey(pt => pt.PostId); modelBuilder.Entity<PostTag>() .HasOne(pt => pt.Tag) .WithMany(t => t.PostTags) .HasForeignKey(pt => pt.TagId); base.OnModelCreating(modelBuilder); } } }
20cdc35f5549e648556ad862d736388e0d481ada
[ "JavaScript", "C#" ]
11
JavaScript
sundeepkamath/PersonalBlog
3a719d4fdaa36c7cfdac6393d1337bd52d99eab8
0e768cb88a6a31068b6215ddffdcc438ca5b1602
refs/heads/master
<repo_name>dushyantrao/CuteCode<file_sep>/cutecode/cutecode.go package cutecode import ( "appengine" "appengine/datastore" "appengine/user" "html/template" "net/http" "time" ) type Code struct { Title string Content string CreatedAt time.Time UpdatedAt time.Time } //caching of templates var indexTemplate = template.Must(template.ParseFiles("templates/layout.html","templates/index.html")) var signinTemplate = template.Must(template.ParseFiles("templates/layout.html","templates/signin.html")) var codeformTemplate = template.Must(template.ParseFiles("templates/layout.html","templates/codeform.html")) var showcodeTemplate = template.Must(template.ParseFiles("templates/layout.html","templates/showcode.html")) //takes appengine Context and returns the datastore key func cutecodeKey(c appengine.Context) *datastore.Key { return datastore.NewKey(c, "CuteCode", "default_cutecode", 0, nil) } func init() { http.HandleFunc("/", handler) //default handler http.HandleFunc("/signin", userHandler) //if route param is signin then invoke userHandler http.HandleFunc("/paste", codeHandler) //if route param is paste then invoke codeHandler http.HandleFunc("/save", saveHandler) //if route param is save then invoke saveHandler } func handler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) q := datastore.NewQuery("CuteCode").Ancestor(cutecodeKey(c)).Order("-CreatedAt").Limit(10) codes := make([]Code, 0, 10) if _, err := q.GetAll(c, &codes); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } err:=indexTemplate.ExecuteTemplate(w,"layout", codes) //this mention of layout stems from the {{layout}} of the layout page. for more http://blog.xcai.net/golang/templates if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func userHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) u := user.Current(c) if u == nil { url, err := user.LoginURL(c, r.URL.String()) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Location", url) w.WriteHeader(http.StatusFound) return } err := signinTemplate.ExecuteTemplate(w, "layout", nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func codeHandler(w http.ResponseWriter, r *http.Request) { err := codeformTemplate.ExecuteTemplate(w, "layout", nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func saveHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) code := Code{ Title: r.FormValue("title"), Content: r.FormValue("content"), } key := datastore.NewIncompleteKey(c, "CuteCode", cutecodeKey(c)) _, err := datastore.Put(c, key, &code) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } templerr := showcodeTemplate.ExecuteTemplate(w,"layout", &code) if templerr != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } <file_sep>/templates/index.html {{define "content"}} <body> <div id="container" class="container-fluid"> <div id="header" class="row-fluid"> <h1 align="center">CuteCode</h1> </div> <div class="well row-fluid"> <a href="/signin" class="btn btn-primary btn-block">Sign in</a> <a href="/paste" class="btn btn-primary btn-block">Share</a> </div> <div id="history" class="row-fluid"> <h3>Code review history - Last 10</h3> <ul class="list-group"> {{range .}} <li class="list-group-item">{{.Title}}</li> {{end}} </ul> </div> </div> </body> {{end}}
809f2f170c673671c37356df1bac6a400fbbdda8
[ "Go", "HTML" ]
2
Go
dushyantrao/CuteCode
84a9e1440702e855e2c50798117fb60f7c561f18
d1bd9db24252047d2474dae33108f73cf7c577ec
refs/heads/master
<repo_name>daria-kopaliani/ENFN<file_sep>/DataSets/Narendra1.R f <- function(k) { if (k < 500) { return ((sin(pi*k/250)))^3 } else { return (0.8*(sin(pi*k/250) + 0.2*sin(pi*k/25))^3) } } data <- rep(0, 2000) for (k in 1 : 2000) { data[k+1] <- (data[k] / (1 + data[k]^2)) + f(k) } plot(1:length(data), data, type="l", col="green") write(data, file = "Narendra1.txt", ncolumns = 1, append = FALSE, sep = " ") #fd <- rep(0, length(data)); #for(k in 2 : length(data)) { # fd[k] <- data[k-1] #} #plot(fd, data, type="l", col="blue")<file_sep>/DataSets/Narendra3.R f <- function(k) { if (k < 2001) { return (cos(2*pi*k/25) + cos(2*pi*k/2))^3 } else { return(sin(2*pi*k/250) + sin(2*pi*k/10))^3 } } data <- rep(0, 3000) for (k in 2 : (length(data) - 1)) { data[k+1] <- data[k]/(1 + (data[k])^2) + f(k) } plot(1:length(data[1800:2700]), data[1800:2700], type="l", col="green") #write(data, file = "Narendra3.txt", ncolumns = 1, append = FALSE, sep = " ") #fd <- rep(0, length(data)) #for(k in 2 : length(data)) { # fd[k] <- data[k-1] #} #plot(fd, data, type="l", col="blue")<file_sep>/DataSets/MackeyGlass.R mackeyglass_eq <- function(x_t, x_t_minus_tau, a, b) { return (-b*x_t + a*x_t_minus_tau/(1 + x_t_minus_tau^10.0)); } mackeyglass_rk4 <- function(x_t, x_t_minus_tau, deltat, a, b) { k1 = deltat*mackeyglass_eq(x_t, x_t_minus_tau, a, b); k2 = deltat*mackeyglass_eq(x_t+0.5*k1, x_t_minus_tau, a, b); k3 = deltat*mackeyglass_eq(x_t+0.5*k2, x_t_minus_tau, a, b); k4 = deltat*mackeyglass_eq(x_t+k3, x_t_minus_tau, a, b); return (x_t + k1/6 + k2/3 + k3/3 + k4/6); } a = 0.2; # value for a in eq (1) b = 0.1; # value for b in eq (1) tau = 17; # delay constant in eq (1) x0 = 1.2; # initial condition: x(t=0)=x0 deltat = 0.1; # time step size (which coincides with the integration step) sample_n = 12000; # total no. of samples, excluding the given initial condition interval = 1; # output is printed at every 'interval' time steps time <- 0; index <- 1; history_length <- floor(tau/deltat) x_history <- rep(0, history_length) x_t <- x0; X <- rep(0, sample_n); # vector of all generated x samples T <- rep(0, sample_n); # vector of time samples for (i in 1 : sample_n) { X[i] <- x_t; if (tau == 0) { x_t_minus_tau <- 0 } else { x_t_minus_tau <- x_history[index]; } x_t_plus_deltat = mackeyglass_rk4(x_t, x_t_minus_tau, deltat, a, b); if (tau != 0) { x_history[index] <- x_t_plus_deltat; index = (index %% history_length) + 1; } time <- time + deltat; T[i] <- time; x_t <- x_t_plus_deltat; } plot(T, X, type="l", col="green") write(X, file = "MackeyGlass.txt", ncolumns = 1, append = FALSE, sep = " ")<file_sep>/ENFN.R normalized_series <- function(directory, n_samples = NA) { range01 <- function(x){(x - min(x))/(max(x) - min(x))} series <- read.csv(directory) if (!is.na(n_samples)) { if (n_samples > nrow(series)) { message("n_samples is larger than total number of rows") } else { series <- series[1:n_samples, ,drop=FALSE] } } series.names <- c("x") series <- range01(series) invisible(series) } ### training set contains n (n = `train_sample_ratio` * series length) samples, testing set contains series length - n samples. ### Each sample in the training set is a vector of `history_length` values, the network is tasked to predict history_length + 1 value train_and_run <- function(series, train_sample_ratio = 0.66, membership_functions = 3, history_length = 10, inference_order = 0, learning_rate = 0.9) { norm_vector <- function(x) sqrt(sum(x^2)) membership_function_value <- function(x, l, c) { if ((l > 1) && (x >= c[l-1]) && (x <= c[l])) { return ((x - c[l-1])/(c[l] - c[l-1])) } else { if (l + 1 <= length(c)) { if ((l <= (length(c) + 1)) && (x >= c[l]) && (x <= c[l+1])) { return ((c[l + 1] - x)/(c[l + 1] - c[l])) } else { return (0) } } else { return (0) } } } inputs <- array(0, dim=c((length(series$x)-history_length), history_length)) obs <- series$x[(history_length+1) : length(series$x)] for (i in 1 : (length(series$x) - history_length)) { inputs[i, ] <- series$x[i : (i + history_length - 1)] } first_test_sample = floor(train_sample_ratio * length(obs)) ## mu - membership function values matrix mu <- array(0, history_length * membership_functions * (inference_order + 1)) ## w - weight matrix w <- array(0, history_length * membership_functions * (inference_order + 1)) sim <- rep(0, length(obs)) e <- rep(0, length(obs)) r <- 0 for (k in seq(along = obs)) { input <- inputs[k,] for (i in seq(along = input)) { for (l in 1 : membership_functions) { c <- seq(0, 1, length.out = membership_functions) muValue <- membership_function_value(input[i], l, c) for (j in 1 : (inference_order + 1)) { mu[(i - 1) * membership_functions + (l - 1) * (inference_order + 1) + j] <- muValue * (input[i]^(j - 1)) } } } sim[k] <- w %*% mu e[k] <- obs[k] - sim[k] ## Training if (k < first_test_sample) { r <- r * learning_rate + (norm_vector(mu))^2 w <- w + e[k] * mu / r } } data <- list(e = e, obs = obs, sim = sim, train_sample_ratio = train_sample_ratio, membership_functions = membership_functions, history_length = history_length, inference_order = inference_order, learning_rate = learning_rate) invisible(data) } visualize <- function(data, first_plot_sample = 1, last_plot_sample = NA, plot_title = "", sub = NA, printErrors = TRUE) { if (is.na(last_plot_sample)) { last_plot_sample <- length(data$obs) } if (is.na(sub)) { sub <- paste(data$membership_functions, " membersip functions, ", data$inference_order, " order fuzzy inference", sep=""); } x <- first_plot_sample : last_plot_sample plot(x, data$obs[first_plot_sample : last_plot_sample], type ="l", col = "green", main = plot_title, sub = sub, ylab = "", xlab = "", ylim = 0:1) lines(x, data$sim[first_plot_sample : last_plot_sample], pch = 22, lty = 2,col = "blue") lines(x, data$e[first_plot_sample : last_plot_sample], type = "l", col = "red") if (!is.na(data$train_sample_ratio)) { first_test_sample = floor(data$train_sample_ratio * length(x)) abline(v = first_test_sample, col = "orange", lty = 1) } if (printErrors) { test_sample_only <- data$train_sample_ratio < 1 if (data$train_sample_ratio < 1) { print(paste("RMSE on test sample -", rmse(data, test_sample_only = TRUE))) print(paste("MSE on test sample -", mse(data, test_sample_only = TRUE))) print(paste("SMAPE on test sample -", smape(data, test_sample_only = TRUE))) } else { print(paste("RMSE -", rmse(data, test_sample_only = FALSE))) print(paste("MSE -", mse(data, test_sample_only = FALSE))) print(paste("SMAPE -", smape(data, test_sample_only = FALSE))) } } } rmse <- function(data, test_sample_only = TRUE) { rmse <- sqrt(mse(data, test_sample_only = test_sample_only)) rmse } mse <- function(data, test_sample_only = TRUE) { range <- 1:length(data$obs) if (test_sample_only) { range <- floor(data$train_sample_ratio * length(data$obs)) : length(data$obs) } mse <- mean((data$sim[range] - data$obs[range])^2, na.rm = TRUE) mse } smape <- function(data, test_sample_only = TRUE) { range <- 1:length(data$obs) if (test_sample_only) { range <- floor(data$train_sample_ratio * length(data$obs)) : length(data$obs) } smape <- (1 / length(range)) * sum (abs(data$sim - data$obs) / (0.5 * (data$sim + data$obs))) smape } #directory <- file.path(getwd(), "DataSets", "MackeyGlass.txt")<file_sep>/DataSets/TimeSeries1.R f <- function(k) { return (sin(k+(sin(k)^2))) } data <- rep(0, 500) for (k in 1 : 500) { data[k+1] <- f(k) } plot(1:length(data), data, type="l", col="green") write(data, file = "TimeSeries1.txt", ncolumns = 1, append = FALSE, sep = " ") #fd <- rep(0, length(data)); #for(k in 2 : length(data)) { # fd[k] <- data[k-1] #} #plot(fd, data, type="l", col="blue")<file_sep>/DataSets/Narendra4.R data <- rep(0, 500) for (k in 1 : 500) { fu <- sin(2*pi*k / 25) + sin(2*pi*k / 10) data[k+1] <- (data[k] / (1 + data[k]^2)) + fu^3 } plot(1:length(data), data, type="l", col="green") #write(data, file = "Narendra4.txt", ncolumns = 1, append = FALSE, sep = " ") #fd <- rep(0, length(data)); #for(k in 2 : length(data)) { # fd[k] <- data[k] - data[k-1] #} #plot(fd, data, type="l", col="blue")<file_sep>/DataSets/Mandelbrot.R data <- rep(0, 1200) data[1] <- 0.2 for (k in 1 : 1500) { data[k+1] <- 4 * data[k] * (1 - data[k]) } plot(1:length(data[1420:1500]), data[1420:1500], type="l", col="green") write(data, file = "Mandelbrot.txt", ncolumns = 1, append = FALSE, sep = " ") #fd <- rep(0, length(data)); #for(k in 2 : length(data)) { # fd[k] <- data[k-1] #} #plot(fd, data, type="l", col="blue")<file_sep>/README.md ENFN ==== Extended Neo Fuzzy Neuron <file_sep>/DataSets/Narendra2.R f <- function(x1, x2, x3, x4, x5) { return ((x1 * x2 * x3 * x5 *(x3 - 1) + x4)/(1 + x3^2 + x2 ^ 2)) } u <- function(k) { if (k < 250) { return (sin(pi*k/25)) } else if (k < 500) { return (1) } else if (k < 750) { return (-1) } else { return (0.4 * sin(pi*k/25) + 0.1 * sin(pi*k/32) + 0.6 * sin(pi*k/10)) } } data <- rep(0, 1500) data[k] <- 0.2 for (k in 1 : 1500) { data[k+3] <- f(data[k+2], data[k+1], data[k], u(k+3), u(k+2)) } plot(1:length(data), data, type="l", col="green") write(data, file = "Narendra2.txt", ncolumns = 1, append = FALSE, sep = " ") #fd <- rep(0, length(data)); #for(k in 2 : length(data)) { # fd[k] <- data[k] - data[k-1] #} #plot(fd, data, type="l", col="blue")
d8b4b43af6605014039f3532b3b63d7a99d41fb7
[ "Markdown", "R" ]
9
R
daria-kopaliani/ENFN
144577c2eaa29db19c43703400aaacd575ee5548
0f9d78d604f5e6dba0ce86c9d56766dae8407f9a
refs/heads/master
<repo_name>uuooooq/OCRN<file_sep>/index.js import React from 'react'; import { AppRegistry, StyleSheet, Text, View, NativeModules, Button, TouchableOpacity } from 'react-native'; var nativeMethods = NativeModules.NativeMethodsCall; var viewMethods = NativeModules.FlexibleSizeExampleViewCall; import Video from 'react-native-video'; let mp4video = require('./test.mp4'); const requireNativeComponent = require('requireNativeComponent'); var FlexibleSizeExampleView = requireNativeComponent('FlexibleSizeExampleView'); class RNHighScores extends React.Component { constructor(props) { super(props); this.state ={ rate: 1, volume: 1, muted: false, resizeMode: 'contain', duration: 0.0, currentTime: 0.0, controls: false, paused: false, skin: 'custom', ignoreSilentSwitch: null, isBuffering: false, showVideo:false, showImagesAnimation:false }; } btnPress(){ //nativeMethods.addEvent('Birthday Party', '4 Privet Drive, Surrey'); this.setState({ showImagesAnimation:true }); viewMethods.addEvent1('Birthday Party', '4 Privet Drive, Surrey'); } // btnPress3(){ // nativeMethods.addEvent('Birthday Party', '4 Privet Drive, Surrey'); // } btnPress1(){ this.setState({ showVideo:true }); this.player.seek(0); } actonPlay(){ this.setState({ showVideo:true, showImagesAnimation:false }); //this.player.seek(0); } videoClick(){ this.setState({ showVideo:false }); } videoEnd(){ this.setState({ showVideo:false }); } render() { var contents = this.props["scores"].map( score => <Text key={score.name}>{score.name}:{score.value}{"\n"}</Text> ); //let videoView = this.state.showVideo ? : null; let videoView = null; if(this.state.showVideo){ videoView = ( <Video source={mp4video} style={styles.fullScreen} ref={(ref) => { this.player = ref }} onEnd={this.videoEnd.bind(this)} /> ); } let imageAnimationView = null; if(this.state.showImagesAnimation){ imageAnimationView = ( <TouchableOpacity onPress={this.actonPlay.bind(this)} > <FlexibleSizeExampleView style={styles.nativeView}> </FlexibleSizeExampleView> </TouchableOpacity> ); } let bgView = null; if(this.state.showImagesAnimation || this.state.showVideo){ bgView = ( <View style={styles.nativeViewBG}/> ); } return ( <View style={styles.container}> {/* <Text style={styles.highScoresTitle}> 2048 High Scores! </Text> <Text style={styles.scores}> {contents} </Text> */} <View style={{marginTop:100}} /> <Text style={styles.highScoresTitle}>这是帧动画演示</Text> <Button onPress={this.btnPress.bind(this)} title="显示" color="blue" accessibilityLabel="Learn more about this purple button" /> {bgView} {imageAnimationView} {videoView} </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, //justifyContent: 'center', //alignItems: 'center', backgroundColor: '#FFFFFF', flexDirection: 'column', }, highScoresTitle: { fontSize: 20, textAlign: 'center', margin: 10, }, scores: { textAlign: 'center', color: '#333333', marginBottom: 5, }, // container: { // flex: 1, // backgroundColor: '#F5FCFF', // }, text: { marginBottom: 20 }, nativeViewBG: { position:'absolute', top: 0, bottom:0, left:0, right:0, backgroundColor:'black', opacity:0.5 }, nativeView: { position:'absolute', top: 0, bottom:0, left:0, right:0 }, backgroundVideo: { position: 'absolute', top: 0, left: 0, bottom: 0, right: 0, }, fullScreen: { position: 'absolute', top: 0, left: 0, bottom: 0, right: 0, } }); // 整体js模块的名称 AppRegistry.registerComponent('OCRN', () => RNHighScores); <file_sep>/ios/build/Build/Intermediates.noindex/OC_RN.build/Debug-iphonesimulator/OC_RN.build/Script-3BAA7841C0B7C89E180DA88C.sh #!/bin/sh "${SRCROOT}/Pods/Target Support Files/Pods-OC_RN/Pods-OC_RN-frameworks.sh" <file_sep>/ios/build/Build/Intermediates.noindex/OC_RN.build/Debug-iphonesimulator/OC_RN.build/Script-82BC46B682F0AC6A0E17FAEB.sh #!/bin/sh "${SRCROOT}/Pods/Target Support Files/Pods-OC_RN/Pods-OC_RN-resources.sh"
79c0b58053287e91739ba30f2b3fafe183f3b376
[ "JavaScript", "Shell" ]
3
JavaScript
uuooooq/OCRN
8f203f59b6b253a7208bca34e7295d7dc38f4428
e0b0aca7b6feef7fdd5eecb670e285bc56eb995d
refs/heads/master
<file_sep>from django.db import models # Create your models here. class Task(models.Model): HIGH = 'high' MIDDLE = 'middle' LOW = 'low' PRIORITY_CHOICES = ( (HIGH, 'high'), (MIDDLE, 'middle'), (LOW, 'low'), ) task = models.CharField(max_length=250) done = models.BooleanField() priority = models.CharField(max_length=10, choices=PRIORITY_CHOICES, default=LOW) <file_sep># Generated by Django 2.0.9 on 2018-10-10 14:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('apis', '0001_initial'), ] operations = [ migrations.AlterField( model_name='task', name='priority', field=models.CharField(choices=[('high', 'high'), ('middle', 'middle'), ('low', 'low')], default='low', max_length=10), ), ] <file_sep># Generated by Django 2.0.9 on 2018-10-10 14:20 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Task', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('task', models.CharField(max_length=250)), ('done', models.BooleanField()), ('priority', models.CharField(choices=[('H', 'high'), ('M', 'middle'), ('L', 'low')], default='L', max_length=1)), ], ), ] <file_sep>from rest_framework import viewsets from .models import Task from .serializers import TaskSerializer class TaskViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing user instances. """ serializer_class = TaskSerializer queryset = Task.objects.all() <file_sep> from django.contrib import admin from django.urls import path from rest_framework.routers import DefaultRouter from apis.views import TaskViewSet router = DefaultRouter() router.register(r'api/tasks', TaskViewSet, basename='task') urlpatterns = router.urls urlpatterns += [ path('admin/', admin.site.urls), ]
58ff25ecc41d7e82135ad4178176e2ed60460ec2
[ "Python" ]
5
Python
JoinCODED/RJSDemo5-To-do-list-BackEnd
870fe096719fee86b19d0fb759862d412bcb31d2
dabb4a73d82de058e9dac0959867856fa0d0407f
refs/heads/master
<file_sep>#include<stdio.h> #include<stdlib.h> int main (int argc, char** argv){ FILE* fp; int matrixSize; int ** matrix; int * matrixsum; //int * unique; int magic= 1; if (argc!= 2){ printf("not enough arguments"); } fp = fopen(argv[1], "r"); if (fp ==NULL){ printf("Error, no input"); return 0; } fscanf(fp,"%d", &matrixSize); matrix = (int**) malloc(matrixSize * sizeof(int*)); // matrix allocated for(int i=0; i< matrixSize; i++){ matrix[i] = (int *) malloc(matrixSize * sizeof(int)); } for(int i=0; i< matrixSize; i++){ for(int j=0; j< matrixSize; j++){ fscanf(fp, "%d", &matrix[i][j]); } } // allocate sum array: int sumsize = 2*matrixSize +2; matrixsum = (int *) malloc(sumsize * sizeof(int)); //error check + make sure its valid input/format //check if numbers are within matrix size ex: 3x3 shouldnt contain 12 or be negative for (int i=0; i<matrixSize; i++){ for(int j =0; j< matrixSize; j++){ if(matrix[i][j] > matrixSize*matrixSize || matrix[i][j]<=0){ magic = 0; break; } } } //check if all the numbers are unique for (int i=1; i<matrixSize; i++){ for(int j =1; j< matrixSize; j++){ if(matrix[0][0] == matrix[i][j]){ magic= 0; break; } } } if(magic == 1){ //summing the matrix: //sum rows int sum=0; for(int j=0; j< matrixSize; j++){ for(int i=0; i< matrixSize; i++){ sum+= matrix[j][i]; } matrixsum[j] = sum; //printf("sum rows is: %d\n", sum ); sum=0; } //sum columns sum =0; for(int i=0; i< matrixSize; i++){ for(int j=0; j< matrixSize; j++){ sum+= matrix[i][j]; } matrixsum[i+ matrixSize] = sum; //printf("sum columnn is: %d\n", sum ); sum=0; } //sum diagonal left to right sum =0; for(int i=0; i< matrixSize; i++){ sum+= matrix[i][i]; } matrixsum[2*matrixSize] = sum; sum=0; //sum diagonal right to left int j = matrixSize - 1; int i=0; while (j>=0){ sum+=matrix[i][j]; i++; j--; } matrixsum[1+2*matrixSize]=sum; sum = 0; //traverse sum array and checking if all sums are equal for(int i =0; i< 2*matrixSize+2; i++){ if(matrixsum[0] != matrixsum[i]){ magic =0; } else{ magic = 1; } } } // output the verdict if(magic == 0){ printf("not-magic"); } if(magic == 1){ printf("magic"); } // free matrix and matrixsum for(int i=0; i< matrixSize; i++){ free(matrix[i]); } free(matrix); free(matrixsum); //close file fclose(fp); return 0; }
c17469389d2df8f86854d355d46a1eea3f15957c
[ "C" ]
1
C
ashvi23/Magic-Matrix
64bb3201c0038a91113112e479c5bd8e1b0c1311
ee260feac323d83bfd31e5091c2afa6312a4fb20
refs/heads/master
<repo_name>dpocheng/CPP-Sobel-Filter-for-edge-detection<file_sep>/OpenMP/Implementation.cpp // Copyright 2017 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /*************************** * <NAME> (pocheng) * * 74157306 * * CompSci 131 Lab 3 A * ***************************/ #include <omp.h> #include <algorithm> #include <cstdlib> #include <cctype> #include <cmath> #include <sstream> #include <fstream> #include <iostream> #include <vector> /* Global variables, Look at their usage in main() */ int image_height; int image_width; int image_maxShades; int inputImage[1000][1000]; int outputImage[1000][1000]; int chunkSize; int thread; int *threadsArray; #define THREADS 2 /* ****************Change and add functions below ***************** */ void compute_sobel_static() { //int x, y, sum, sumx, sumy; int x, y; int GX[3][3], GY[3][3]; int start_of_chunk = 0; int end_of_chunk = image_height; /* 3x3 Sobel mask for X Dimension. */ GX[0][0] = -1; GX[0][1] = 0; GX[0][2] = 1; GX[1][0] = -2; GX[1][1] = 0; GX[1][2] = 2; GX[2][0] = -1; GX[2][1] = 0; GX[2][2] = 1; /* 3x3 Sobel mask for Y Dimension. */ GY[0][0] = 1; GY[0][1] = 2; GY[0][2] = 1; GY[1][0] = 0; GY[1][1] = 0; GY[1][2] = 0; GY[2][0] = -1; GY[2][1] = -2; GY[2][2] = -1; #pragma omp parallel shared(inputImage, outputImage, chunkSize, threadsArray) { #pragma omp for schedule(static, chunkSize) nowait for (x = start_of_chunk; x < end_of_chunk; x++) { threadsArray[x] = omp_get_thread_num(); for (y = 0; y < image_width; y++) { //sumx = 0; //sumy = 0; int sum = 0, sumx = 0, sumy = 0; /* For handling image boundaries */ if(x == 0 || x == (image_height-1) || y == 0 || y == (image_width-1)) { sum = 0; } else { /* Gradient calculation in X Dimension */ for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { sumx += (inputImage[x+i][y+j] * GX[i+1][j+1]); } } /* Gradient calculation in Y Dimension */ for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { sumy += (inputImage[x+i][y+j] * GY[i+1][j+1]); } } /* Gradient magnitude */ sum = (abs(sumx) + abs(sumy)); } /* outputImage[x][y] = (0 <= sum <= 255); */ if (sum < 0) { outputImage[x][y] = 0; } else if (sum > 255) { outputImage[x][y] = 255; } else { outputImage[x][y] = sum; } } } } } void compute_sobel_dynamic() { //int x, y, sum, sumx, sumy; int x, y; int GX[3][3], GY[3][3]; int start_of_chunk = 0; int end_of_chunk = image_height; /* 3x3 Sobel mask for X Dimension. */ GX[0][0] = -1; GX[0][1] = 0; GX[0][2] = 1; GX[1][0] = -2; GX[1][1] = 0; GX[1][2] = 2; GX[2][0] = -1; GX[2][1] = 0; GX[2][2] = 1; /* 3x3 Sobel mask for Y Dimension. */ GY[0][0] = 1; GY[0][1] = 2; GY[0][2] = 1; GY[1][0] = 0; GY[1][1] = 0; GY[1][2] = 0; GY[2][0] = -1; GY[2][1] = -2; GY[2][2] = -1; #pragma omp parallel shared(inputImage, outputImage, chunkSize, threadsArray) { #pragma omp for schedule(dynamic, chunkSize) nowait for(x = start_of_chunk; x < end_of_chunk; x++) { threadsArray[x] = omp_get_thread_num(); for(y = 0; y < image_width; y++) { //sumx = 0; //sumy = 0; int sum = 0, sumx = 0, sumy = 0; /* For handling image boundaries */ if(x == 0 || x == (image_height-1) || y == 0 || y == (image_width-1)) { sum = 0; } else { /* Gradient calculation in X Dimension */ for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { sumx += (inputImage[x+i][y+j] * GX[i+1][j+1]); } } /* Gradient calculation in Y Dimension */ for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { sumy += (inputImage[x+i][y+j] * GY[i+1][j+1]); } } /* Gradient magnitude */ sum = (abs(sumx) + abs(sumy)); } /* outputImage[x][y] = (0 <= sum <= 255); */ if (sum < 0) { outputImage[x][y] = 0; } else if (sum > 255) { outputImage[x][y] = 255; } else { outputImage[x][y] = sum; } } } } } /* **************** Change the function below if you need to ***************** */ int main(int argc, char* argv[]) { if (argc != 5) { std::cout << "ERROR: Incorrect number of arguments. Format is: <Input image filename> <Output image filename> <Chunk size> <a1/a2>" << std::endl; return 0; } std::ifstream file(argv[1]); if(!file.is_open()) { std::cout << "ERROR: Could not open file " << argv[1] << std::endl; return 0; } chunkSize = std::atoi(argv[3]); std::cout << "Detect edges in " << argv[1] << " using OpenMP threads\n" << std::endl; /* ******Reading image into 2-D array below******** */ std::string workString; /* Remove comments '#' and check image format */ while (std::getline(file, workString)) { if (workString.at(0) != '#') { if (workString.at(1) != '2') { std::cout << "Input image is not a valid PGM image" << std::endl; return 0; } else { break; } } else { continue; } } /* Check image size */ while (std::getline(file,workString)) { if (workString.at(0) != '#') { std::stringstream stream(workString); int n; stream >> n; image_width = n; stream >> n; image_height = n; break; } else { continue; } } /* Check image max shades */ while (std::getline(file,workString)) { if (workString.at(0) != '#') { std::stringstream stream(workString); stream >> image_maxShades; break; } else { continue; } } /* Fill input image matrix */ int pixel_val; for (int i = 0; i < image_height; i++) { if (std::getline(file,workString) && workString.at(0) != '#') { std::stringstream stream(workString); for (int j = 0; j < image_width; j++) { if(!stream) { break; } stream >> pixel_val; inputImage[i][j] = pixel_val; } } else { continue; } } /************ Call functions to process image *********/ std::string opt = argv[4]; if(!opt.compare("a1")) { threadsArray = new int[image_height]; omp_set_num_threads(THREADS); double dtime_static = omp_get_wtime(); compute_sobel_static(); dtime_static = omp_get_wtime() - dtime_static; //for (int row = 0; row < image_height; row++) { // if (row == 0) { // thread = threadsArray[0]; // } // else { // if (thread != threadsArray[row]) { // thread = threadsArray[row]; // std::cout << "Chunk starting at row " << row << " is processing by Thread " << thread << std::endl; // } // } //} std::cout << "Part A1 uses " << dtime_static << " to run." << std::endl; } else { threadsArray = new int[image_height]; omp_set_num_threads(THREADS); double dtime_dyn = omp_get_wtime(); compute_sobel_dynamic(); dtime_dyn = omp_get_wtime() - dtime_dyn; //for (int row = 0; row < image_height; row++) { // if (row == 0) { // thread = threadsArray[0]; // } // else { // if (thread != threadsArray[row]) { // thread = threadsArray[row]; // std::cout << "Chunk starting at row " << row << " is processing by Thread " << thread << std::endl; // } // } //} std::cout << "Part A2 uses " << dtime_dyn << " to run." << std::endl; } /* ********Start writing output to your file************ */ std::ofstream ofile(argv[2]); if (ofile.is_open()) { ofile << "P2" << "\n" << image_width << " " << image_height << "\n" << image_maxShades << "\n"; for (int i = 0; i < image_height; i++) { for (int j = 0; j < image_width; j++) { ofile << outputImage[i][j] << " "; } ofile << "\n"; } } else { std::cout << "ERROR: Could not open output file " << argv[2] << std::endl; return 0; } return 0; }<file_sep>/MPI/ImplementationA.cpp // Copyright 2017 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "mpi.h" #include <algorithm> #include <cstdlib> #include <cctype> #include <cmath> #include <sstream> #include <fstream> #include <iostream> #include <vector> #define send_data_tag 2001 #define return_data_tag 2002 ***************** Add/Change the functions(including processImage) here ********************* // NOTE: Some arrays are linearized in the skeleton below to ease the MPI Data Communication // i.e. A[x][y] become A[x*total_number_of_columns + y] int* processImage(int* inputImage, int processId, int num_processes, int image_height, int image_width){ int x, y, sum, sumx, sumy; int GX[3][3], GY[3][3]; /* 3x3 Sobel masks. */ GX[0][0] = -1; GX[0][1] = 0; GX[0][2] = 1; GX[1][0] = -2; GX[1][1] = 0; GX[1][2] = 2; GX[2][0] = -1; GX[2][1] = 0; GX[2][2] = 1; GY[0][0] = 1; GY[0][1] = 2; GY[0][2] = 1; GY[1][0] = 0; GY[1][1] = 0; GY[1][2] = 0; GY[2][0] = -1; GY[2][1] = -2; GY[2][2] = -1; //chunkSize is the number of rows to be computed by this process int chunkSize; int* partialOutputImage; for( x = start_of_chunk; x < end_of_chunk; x++ ){ for( y = 0; y < image_width; y++ ){ sumx = 0; sumy = 0; //Change boundary cases as required if(x==0 || x==(image_height-1) || y==0 || y==(image_width-1)) sum = 0; else{ for(int i=-1; i<=1; i++) { for(int j=-1; j<=1; j++){ sumx += (inputImage[(x+i)*image_width+ (y+j)] * GX[i+1][j+1]); } } for(int i=-1; i<=1; i++) { for(int j=-1; j<=1; j++){ sumy += (inputImage[(x+i)*image_width+ (y+j)] * GY[i+1][j+1]); } } sum = (abs(sumx) + abs(sumy)); } partialOutputImage[x*image_width + y] = (0 <= sum <= 255); } } return partialOutputImage; } int main(int argc, char* argv[]) { int processId, num_processes, image_height, image_width, image_maxShades, root_process, child_id; int *inputImage, *outputImage; int *partialImage, *tempImage; int count_recv, count_return; root_process = 0; // Setup MPI MPI_Init( &argc, &argv ); MPI_Comm_rank( MPI_COMM_WORLD, &processId); MPI_Comm_size( MPI_COMM_WORLD, &num_processes); chunk_size = image_height / num_processes; if(argc != 3) { if(processId == 0) std::cout << "ERROR: Incorrect number of arguments. Format is: <Input image filename> <Output image filename>" << std::endl; MPI_Finalize(); return 0; } if(processId == 0) { std::ifstream file(argv[1]); if(!file.is_open()) { std::cout << "ERROR: Could not open file " << argv[1] << std::endl; MPI_Finalize(); return 0; } std::cout << "Detect edges in " << argv[1] << " using " << num_processes << " processes\n" << std::endl; std::string workString; /* Remove comments '#' and check image format */ while(std::getline(file,workString)) { if( workString.at(0) != '#' ){ if( workString.at(1) != '2' ){ std::cout << "Input image is not a valid PGM image" << std::endl; return 0; } else { break; } } else { continue; } } /* Check image size */ while(std::getline(file,workString)) { if( workString.at(0) != '#' ){ std::stringstream stream(workString); int n; stream >> n; image_width = n; stream >> n; image_height = n; break; } else { continue; } } inputImage = new int[image_height*image_width]; outputImage = new int[image_height*image_width]; tempImage = new int[image_height*image_width]; partialImage = new int[image_height*image_width]; /* Check image max shades */ while(std::getline(file,workString)) { if( workString.at(0) != '#' ){ std::stringstream stream(workString); stream >> image_maxShades; break; } else { continue; } } /* Fill input image matrix */ int pixel_val; for( int i = 0; i < image_height; i++ ) { if( std::getline(file,workString) && workString.at(0) != '#' ){ std::stringstream stream(workString); for( int j = 0; j < image_width; j++ ){ if( !stream ) break; stream >> pixel_val; inputImage[(i*image_width)+j] = pixel_val; } } else { continue; } } } // Done with reading image using process 0 if(processId == 0){ // distribute a portion to each child process for(child_id = 1; child_id < num_processes; child_id++) { start_of_chunk = child_id*chunk_size; end_of_chunk = (child_id + 1)*chunk_size - 1; int count = chunk_size * image_width; int start_index = child_id * count; // check last chuck's end point if((image_height- end_of_chunk) < chunk_size) { end_of_chunk = image_height - 1; int rows = end_of_chunk - start_of_chunk + 1; // overwrite count value count = rows * image_width; } // sending segments MPI_Send(&count, 1, MPI_INT, child_id, send_data_tag, MPI_COMM_WORLD); MPI_Send(&inputImage[start_index], count, MPI_INT, child_id, send_data_tag, MPI_COMM_WORLD); } // process image in the segment assigned to the root process for(int i = 0; i < (chunk_size * image_width); i++){ tempImage[i] = inputImage[i]; } outputImage = processImage(tempImage, processId, num_processes, image_height, image_width); // receive partial image and add them to outputImage for(child_id = 1; child_id < num_processes; child_id++) { MPI_Recv (&count_return, 1, MPI_INT, MPI_ANY_SOURCE, return_data_tag, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv (&partialImage, count_return, MPI_INT, MPI_ANY_SOURCE, return_data_tag, MPI_COMM_WORLD, MPI_STATUS_IGNORE); for(int i = 0; i < ;i++){ outputImage[child_id*image_width + 1] = partialImage[i]; } } } else{ // receive segments from root process MPI_Recv(&count_recv, 1, MPI_INT, root_process, send_data_tag, MPI_COMM_WORLD, MPI_STATUS_IGNORE); MPI_Recv(&tempImage, count_recv, MPI_INT, root_process, send_data_tag, MPI_COMM_WORLD, MPI_STATUS_IGNORE); // process image in the segment assigned to each child process partialImage = processImage(tempImage, processId, num_processes, image_height, image_width); // send partial image to the root process MPI_Send(&count_recv, 1, MPI_INT, root_process, return_data_tag, MPI_COMM_WORLD); MPI_Send(&partialImage, count_recv, MPI_INT, root_process, return_data_tag, MPI_COMM_WORLD); } ***************** Add code as per your requirement below ********************* if(processId == 0) { /* Start writing output to your file */ std::ofstream ofile(argv[2]); if( ofile.is_open() ) { ofile << "P2" << "\n" << image_width << " " << image_height << "\n" << image_maxShades << "\n"; for( int i = 0; i < image_height; i++ ) { for( int j = 0; j < image_width; j++ ){ ofile << outputImage[(i*image_width)+j] << " "; } ofile << "\n"; } } else { std::cout << "ERROR: Could not open output file " << argv[2] << std::endl; return 0; } } MPI_Finalize(); return 0; }<file_sep>/pthread/Implementation.cpp // Copyright 2017 <NAME> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /*************************** * <NAME> (pocheng) * * 74157306 * * CompSci 131 Lab 1 B * ***************************/ #include <algorithm> #include <cstdlib> #include <cctype> #include <cmath> #include <sstream> #include <fstream> #include <iostream> #include <vector> #include <mutex> #include <thread> /* Global variables, Look at their usage in main() */ int image_height; int image_width; int image_maxShades; int inputImage[1000][1000]; int outputImage[1000][1000]; int num_threads; int chunkSize; int maxChunk; int nextAvailableChunk; std::mutex mutexes; /* ****************Change and add functions below ***************** */ int get_dynamic_chunk() { mutexes.lock(); int N = chunkSize * nextAvailableChunk; nextAvailableChunk += 1; mutexes.unlock(); return N; } void sobel_algorithm(int dynamic_chunk) { int sumx, sumy, sum; int maskX[3][3]; int maskY[3][3]; /* 3x3 Sobel mask for X Dimension. */ maskX[0][0] = -1; maskX[0][1] = 0; maskX[0][2] = 1; maskX[1][0] = -2; maskX[1][1] = 0; maskX[1][2] = 2; maskX[2][0] = -1; maskX[2][1] = 0; maskX[2][2] = 1; /* 3x3 Sobel mask for Y Dimension. */ maskY[0][0] = 1; maskY[0][1] = 2; maskY[0][2] = 1; maskY[1][0] = 0; maskY[1][1] = 0; maskY[1][2] = 0; maskY[2][0] = -1; maskY[2][1] = -2; maskY[2][2] = -1; for (int x = dynamic_chunk; x < (dynamic_chunk+chunkSize); ++x) { for (int y = 0; y < image_width; ++y){ sumx = 0; sumy = 0; /* For handling image boundaries */ if (x == 0 || x == ((dynamic_chunk+chunkSize)-1) || y == 0 || y == (image_width-1)) { sum = 0; } else { /* Gradient calculation in X Dimension */ for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++){ sumx += (inputImage[x+i][y+j] * maskX[i+1][j+1]); } } /* Gradient calculation in Y Dimension */ for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++){ sumy += (inputImage[x+i][y+j] * maskY[i+1][j+1]); } } /* Gradient magnitude */ sum = (abs(sumx) + abs(sumy)); } /* outputImage[x][y] = (0 <= sum <= 255); */ if (sum >= 0 && sum <= 255) { outputImage[x][y] = sum; } else if (sum > 255) { outputImage[x][y] = 0; } else if (sum < 0) { outputImage[x][y] = 255; } } } } void compute_chunk() { int X = get_dynamic_chunk(); sobel_algorithm(X); } void dispatch_threads() { std::vector<std::thread> threads; nextAvailableChunk = 0; for (int i = 0; i < num_threads; i++) { threads.push_back(std::thread(compute_chunk)); } for (int i = 0; i < num_threads; i++) { threads[i].join(); } } /* ****************Need not to change the function below ***************** */ int main(int argc, char* argv[]) { if(argc != 5) { std::cout << "ERROR: Incorrect number of arguments. Format is: <Input image filename> <Output image filename> <Threads#> <Chunk size>" << std::endl; return 0; } std::ifstream file(argv[1]); if(!file.is_open()) { std::cout << "ERROR: Could not open file " << argv[1] << std::endl; return 0; } num_threads = std::atoi(argv[3]); chunkSize = std::atoi(argv[4]); std::cout << "Detect edges in " << argv[1] << " using " << num_threads << " threads\n" << std::endl; /* ******Reading image into 2-D array below******** */ std::string workString; /* Remove comments '#' and check image format */ while(std::getline(file,workString)) { if( workString.at(0) != '#' ){ if( workString.at(1) != '2' ){ std::cout << "Input image is not a valid PGM image" << std::endl; return 0; } else { break; } } else { continue; } } /* Check image size */ while(std::getline(file,workString)) { if( workString.at(0) != '#' ){ std::stringstream stream(workString); int n; stream >> n; image_width = n; stream >> n; image_height = n; break; } else { continue; } } /* maxChunk is total number of chunks to process */ maxChunk = ceil((float)image_height/chunkSize); /* Check image max shades */ while(std::getline(file,workString)) { if( workString.at(0) != '#' ){ std::stringstream stream(workString); stream >> image_maxShades; break; } else { continue; } } /* Fill input image matrix */ int pixel_val; for( int i = 0; i < image_height; i++ ) { if( std::getline(file,workString) && workString.at(0) != '#' ){ std::stringstream stream(workString); for( int j = 0; j < image_width; j++ ){ if( !stream ) break; stream >> pixel_val; inputImage[i][j] = pixel_val; } } else { continue; } } /************ Function that creates threads and manage dynamic allocation of chunks *********/ dispatch_threads(); /* ********Start writing output to your file************ */ std::ofstream ofile(argv[2]); if( ofile.is_open() ) { ofile << "P2" << "\n" << image_width << " " << image_height << "\n" << image_maxShades << "\n"; for( int i = 0; i < image_height; i++ ) { for( int j = 0; j < image_width; j++ ){ ofile << outputImage[i][j] << " "; } ofile << "\n"; } } else { std::cout << "ERROR: Could not open output file " << argv[2] << std::endl; return 0; } return 0; }
387e090958f5e4c173673218f07599f719685615
[ "C++" ]
3
C++
dpocheng/CPP-Sobel-Filter-for-edge-detection
609fb98f010af60ee66a1cbb3f1963602f153634
87482efe0acd35fccdfeb1b116f272167a2e15aa
refs/heads/master
<file_sep>// from data.js var tableData = data; var tbody = d3.select("tbody"); function createTable(data) { // First, clear out any existing data tbody.html(""); // Next, loop through each object in the data // and append a row and cells for each value in the row data.forEach((dataRow) => { // Append a row to the table body var row = tbody.append("tr"); // Loop through each field in the dataRow and add // each value as a table cell (td) Object.values(dataRow).forEach((value) => { var cell = row.append("td"); cell.text(value); }); }); } function handleClick() { // Prevent form from refreshing page d3.event.preventDefault(); // Collect date/time from filter var date = d3.select("#datetime").property("value"); var filteredData = tableData; // confirm date exists and then filter //console.log(date) if (date) { filteredData = filteredData.filter(row => row.datetime === date); } createTable(filteredData); } // Rebuild table uisng filtered data //createTable(filteredData); // Event listner d3.selectAll("#filter-btn").on("click", handleClick); // Build table upon page reload createTable(tableData);
29938c4732d84d08b8bd62a2d9981e3df09cc33e
[ "JavaScript" ]
1
JavaScript
TrevorKent/UFO-Sightings
da05d52b184d75cf9363ca5da5e6caf5cb31a293
c35e822105b520eebc94018580bf4aec55ac254a
refs/heads/main
<repo_name>inspiredminds/contao-unified-news-aliases<file_sep>/src/Resources/contao/languages/en/tl_news_archive.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ $GLOBALS['TL_LANG']['tl_news_archive']['use_unified_aliases'] = ['Use unified aliases', 'Enables the usage for unified aliases in the front end.']; <file_sep>/src/ModuleNewsHelper.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ namespace InspiredMinds\ContaoUnifiedNewsAliases; use Contao\ModuleNews; use Contao\NewsModel; /** * Helper class to expose ModuleNews::generateLink(). */ class ModuleNewsHelper extends ModuleNews { public function __construct() { // Noop } public function generateHtmlLink(string $linkText, NewsModel $news, bool $addArchive = false, $isReadMore = false): string { return $this->generateLink($linkText, $news, $addArchive, $isReadMore); } protected function compile(): void { // Noop } } <file_sep>/src/EventListener/AdjustNewsLinkListener.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ namespace InspiredMinds\ContaoUnifiedNewsAliases\EventListener; use Contao\CoreBundle\ServiceAnnotation\Hook; use Contao\FrontendTemplate; use Contao\News; use Contao\NewsModel; use InspiredMinds\ContaoUnifiedNewsAliases\ModuleNewsHelper; use InspiredMinds\ContaoUnifiedNewsAliases\UnifiedNewsAliases; use Symfony\Contracts\Translation\TranslatorInterface; /** * @Hook("parseArticles") */ class AdjustNewsLinkListener { private $unifiedNewsAliases; private $newsHelper; private $translator; public function __construct(UnifiedNewsAliases $unifiedNewsAliases, TranslatorInterface $translator) { $this->unifiedNewsAliases = $unifiedNewsAliases; $this->newsHelper = new ModuleNewsHelper(); $this->translator = $translator; } public function __invoke(FrontendTemplate $template, array $newsEntry): void { $news = NewsModel::findById($newsEntry['id']); if (!$this->unifiedNewsAliases->isUnifiedAliasEnabled($news) || $this->unifiedNewsAliases->isMainNews($news)) { return; } $mainNews = $this->unifiedNewsAliases->getMainNews($news); if (null === $mainNews) { return; } $news->preventSaving(); $news->id = 'clone-'.$newsEntry['id']; $news->alias = $mainNews->alias; $template->linkHeadline = $this->newsHelper->generateHtmlLink($news->headline, $news); $template->more = $this->newsHelper->generateHtmlLink($this->translator->trans('MSC.more', [], 'contao_default'), $news, false, true); $template->link = News::generateNewsUrl($news); } } <file_sep>/src/Resources/contao/languages/de/modules.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ use InspiredMinds\ContaoUnifiedNewsAliases\Controller\FrontendModule\NewsReaderModuleController; $GLOBALS['TL_LANG']['FMD'][NewsReaderModuleController::TYPE] = [ $GLOBALS['TL_LANG']['FMD']['newsreader'][0].' für vereinheitlichte Aliase', 'Dieser Nachrichtenleser erlaubt die Darstellung von Nachrichten über den vereinheitlichten Nachrichtenalias (also den Nachrichten-Alias aus dem Hauptarchiv).', ]; <file_sep>/src/EventListener/AdjustNewsArchiveDcaListener.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ namespace InspiredMinds\ContaoUnifiedNewsAliases\EventListener; use Contao\CoreBundle\DataContainer\PaletteManipulator; use Contao\CoreBundle\ServiceAnnotation\Callback; use Contao\DataContainer; use Contao\NewsArchiveModel; /** * @Callback(table="tl_news_archive", target="config.onload", priority=-32) */ class AdjustNewsArchiveDcaListener { public function __invoke(DataContainer $dc): void { $GLOBALS['TL_DCA']['tl_news_archive']['fields']['master']['eval']['submitOnChange'] = true; if (!$dc->id) { return; } $archive = NewsArchiveModel::findById($dc->id); if (null === $archive || (bool) $archive->master) { return; } PaletteManipulator::create() ->addField('use_unified_aliases', 'language_legend', PaletteManipulator::POSITION_APPEND) ->applyToPalette('default', 'tl_news_archive') ; } } <file_sep>/src/EventListener/AdjustCustomTplOptionsCallback.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ namespace InspiredMinds\ContaoUnifiedNewsAliases\EventListener; use Contao\Controller; use Contao\CoreBundle\ServiceAnnotation\Callback; use Contao\DataContainer; use Contao\ModuleModel; use InspiredMinds\ContaoUnifiedNewsAliases\Controller\FrontendModule\NewsReaderModuleController; /** * @Callback(table="tl_module", target="config.onload") */ class AdjustCustomTplOptionsCallback { public function __invoke(DataContainer $dc): void { $module = ModuleModel::findById($dc->id); if (null === $module || NewsReaderModuleController::TYPE !== $module->type) { return; } $GLOBALS['TL_DCA']['tl_module']['fields']['customTpl']['options_callback'] = function () { return Controller::getTemplateGroup('mod_newsreader_', [], 'mod_newsreader'); }; } } <file_sep>/src/ContaoUnifiedNewsAliasesBundle.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ namespace InspiredMinds\ContaoUnifiedNewsAliases; use Symfony\Component\HttpKernel\Bundle\Bundle; class ContaoUnifiedNewsAliasesBundle extends Bundle { } <file_sep>/src/Controller/FrontendModule/NewsReaderModuleController.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ namespace InspiredMinds\ContaoUnifiedNewsAliases\Controller\FrontendModule; use Contao\CoreBundle\Exception\RedirectResponseException; use Contao\CoreBundle\ServiceAnnotation\FrontendModule; use Contao\Input; use Contao\ModuleModel; use Contao\ModuleNewsReader; use Contao\News; use Contao\NewsModel; use InspiredMinds\ContaoUnifiedNewsAliases\UnifiedNewsAliases; use Symfony\Component\HttpFoundation\Response; /** * @FrontendModule(NewsReaderModuleController::TYPE, category="news", template="mod_newsreader") */ class NewsReaderModuleController extends ModuleNewsReader { public const TYPE = 'newsreader_unified_aliases'; private $unifiedAliases; public function __construct(UnifiedNewsAliases $unifiedAliases) { $this->unifiedAliases = $unifiedAliases; } public function __invoke(ModuleModel $model, string $section): Response { parent::__construct($model, $section); return new Response($this->generate()); } protected function compile(): void { $this->overrideItems(); parent::compile(); } private function overrideItems(): void { $news = NewsModel::findOneByAlias(Input::get('items', false, true)); // Check if this is a valid news alias if (null === $news) { return; } // Check if unified aliases feature is enabled for this news if (!$this->unifiedAliases->isUnifiedAliasEnabled($news)) { return; } // Get the actual news for the current language $actualNews = $this->unifiedAliases->getNewsForCurrentLanguage($news); if (null === $actualNews) { return; } // Check if this news is actually allowed here if (null === NewsModel::findPublishedByParentAndIdOrAlias($actualNews->alias, $this->news_archives)) { return; } // Redirect in case the detail URL was accessed with the regular alias of the news if ($this->unifiedAliases->isCurrentLanguage($news) && !$this->unifiedAliases->isMainNews($news)) { $this->redirectToMainNewsUrl($news); } // Override the "items" variable Input::setGet('items', $actualNews->alias); } private function redirectToMainNewsUrl(NewsModel $news): void { $mainNews = $this->unifiedAliases->getMainNews($news); if (null === $mainNews) { return; } $news->preventSaving(); $news->id = 'clone-'.$news->id; $news->alias = $mainNews->alias; throw new RedirectResponseException(News::generateNewsUrl($news, false, true), Response::HTTP_MOVED_PERMANENTLY); } } <file_sep>/src/EventListener/ModuleNewsreaderOptionsCallback.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ namespace InspiredMinds\ContaoUnifiedNewsAliases\EventListener; use Contao\CoreBundle\ServiceAnnotation\Callback; use Doctrine\DBAL\Connection; /** * @Callback(table="tl_module", target="fields.news_readerModule.options", priority=100) */ class ModuleNewsreaderOptionsCallback { private $db; public function __construct(Connection $db) { $this->db = $db; } public function __invoke(): array { $options = []; $modules = $this->db ->executeQuery("SELECT m.id, m.name, t.name AS theme FROM tl_module m LEFT JOIN tl_theme t ON m.pid=t.id WHERE m.type LIKE 'newsreader%' ORDER BY t.name, m.name") ->fetchAll() ; if (false === $modules) { return $options; } foreach ($modules as $module) { $options[$module['theme']][$module['id']] = $module['name'].' (ID '.$module['id'].')'; } return $options; } } <file_sep>/src/Resources/contao/dca/tl_news_archive.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ $GLOBALS['TL_DCA']['tl_news_archive']['fields']['use_unified_aliases'] = [ 'inputType' => 'checkbox', 'eval' => ['tl_class' => 'w50 clr'], 'sql' => ['type' => 'boolean', 'default' => false], ]; <file_sep>/README.md [![](https://img.shields.io/packagist/v/inspiredminds/contao-unified-news-aliases.svg)](https://packagist.org/packages/inspiredminds/contao-unified-news-aliases) [![](https://img.shields.io/packagist/dt/inspiredminds/contao-unified-news-aliases.svg)](https://packagist.org/packages/inspiredminds/contao-unified-news-aliases) Contao Unified News Aliases =========================== This Contao extensions allows you to use the same news alias for the same news article translated into different languages. In Contao, each and every news article must have a unique alias. However there are use cases where you might want to use the same alias for translated news articles. This extension allows you to always use the alias of the main news archive in the front end. _Note:_ this extension does not actually allow you to _save_ duplicate aliases in the back end. The extension only affects the news URLs of news modules in the front end and provides an additional newsreader module. ## Usage Assuming that the language settings of your news archives are already properly set up there are only two steps necessary to use the functionality of this extension: 1. Enable the unified aliases in the language settings of your main news archive. 2. Use the _Newsreader for unified aliases_ module instead of the regular newsreader module. ## Attributions Development funded by [interAKTIV.net GmbH](https://www.interaktiv.net/). <file_sep>/src/Resources/contao/languages/de/tl_news_archive.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ $GLOBALS['TL_LANG']['tl_news_archive']['use_unified_aliases'] = ['Vereinheitlichte Aliase benutzen', 'Aktiviert die Benutzung vereinheitlichter Nachrichtenaliase für dieses Archiv.']; <file_sep>/src/UnifiedNewsAliases.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ namespace InspiredMinds\ContaoUnifiedNewsAliases; use Contao\NewsArchiveModel; use Contao\NewsModel; use Contao\PageModel; use Symfony\Component\HttpFoundation\RequestStack; class UnifiedNewsAliases { private $requestStack; public function __construct(RequestStack $requestStack) { $this->requestStack = $requestStack; } /** * Check whether the main news archive for the given news has unified aliases enabled. */ public function isUnifiedAliasEnabled(NewsModel $news): bool { $archive = NewsArchiveModel::findById((int) $news->pid); if ((int) $archive->master > 0) { $archive = NewsArchiveModel::findById((int) $archive->master); } if (null === $archive) { return false; } return (bool) $archive->use_unified_aliases; } /** * Checks whethe the given news article is for the current language. */ public function isCurrentLanguage(NewsModel $news): bool { $archive = NewsArchiveModel::findById((int) $news->pid); if (null === $archive) { throw new \RuntimeException('Could not find archive for news ID "'.$news->id.'".'); } $target = PageModel::findWithDetails($archive->jumpTo); if (null === $target) { throw new \RuntimeException('Could not find target page for news archive ID "'.$archive->id.'".'); } $request = $this->requestStack->getCurrentRequest(); if (null === $request) { throw new \RuntimeException('Could not get current request.'); } return $target->rootLanguage === $request->getLocale(); } /** * Checks whether the given news is the main news article. */ public function isMainNews(NewsModel $news): bool { $archive = NewsArchiveModel::findById($news->pid); if (null === $archive) { throw new \RuntimeException('Could not find archive for news ID "'.$news->id.'".'); } return 0 === (int) $archive->master; } /** * Returns the main news record for the given news, if applicable. */ public function getMainNews(NewsModel $news): ?NewsModel { if (0 === (int) $news->languageMain) { return null; } return NewsModel::findById((int) $news->languageMain); } /** * Returns the associated news for the given news and language. */ public function getNewsForLanguage(NewsModel $news, string $language): ?NewsModel { $searchId = (int) ($news->languageMain ?: $news->id); $t = NewsModel::getTable(); $articles = NewsModel::findBy( ["($t.id = ? OR $t.languageMain = ?)"], [$searchId, $searchId] ); if (null === $articles) { return null; } foreach ($articles as $article) { $archive = NewsArchiveModel::findById((int) $article->pid); if (null === $archive) { continue; } $target = PageModel::findWithDetails($archive->jumpTo); if (null === $target) { return null; } if ($target->rootLanguage === $language) { return $article; } } return null; } /** * Returns the associated news for the given news and the current language. */ public function getNewsForCurrentLanguage(NewsModel $news): ?NewsModel { $request = $this->requestStack->getCurrentRequest(); if (null === $request) { throw new \RuntimeException('Could not get current request.'); } return $this->getNewsForLanguage($news, $request->getLocale()); } } <file_sep>/src/EventListener/AdjustChangeLanguageNavigationListener.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ namespace InspiredMinds\ContaoUnifiedNewsAliases\EventListener; use Contao\CoreBundle\ServiceAnnotation\Hook; use Contao\Input; use Contao\NewsArchiveModel; use Contao\NewsModel; use InspiredMinds\ContaoUnifiedNewsAliases\UnifiedNewsAliases; use Terminal42\ChangeLanguage\Event\ChangelanguageNavigationEvent; /** * @Hook("changelanguageNavigation", priority=-100) */ class AdjustChangeLanguageNavigationListener { private $unifiedAliases; public function __construct(UnifiedNewsAliases $unifiedAliases) { $this->unifiedAliases = $unifiedAliases; } public function __invoke(ChangelanguageNavigationEvent $event): void { $alias = Input::get('auto_item', false, true); if (empty($alias)) { return; } global $objPage; $archives = NewsArchiveModel::findBy('jumpTo', $objPage->id); // Check if any news archive have this page as its target page if (null === $archives) { return; } // Check if unified aliases feature is enabled for this news $currentNews = NewsModel::findOneByAlias($alias); if (null === $currentNews) { return; } if (!$this->unifiedAliases->isUnifiedAliasEnabled($currentNews)) { return; } // Get the actual news for the current language $actualNews = $this->unifiedAliases->getNewsForCurrentLanguage($currentNews); if (null === $actualNews) { return; } // Check if this news is actually allowed here if (!\in_array((int) $actualNews->pid, array_map('intval', $archives->fetchEach('id')), true)) { return; } // Get the main news for the current news $mainNews = $this->unifiedAliases->getMainNews($currentNews); if (null === $mainNews) { if (!$this->unifiedAliases->isMainNews($currentNews)) { return; } $mainNews = $currentNews; } // Override the "items" URL attribute with the alias of the main news $event->getUrlParameterBag()->setUrlAttribute('items', $mainNews->alias); } } <file_sep>/src/Resources/contao/dca/tl_module.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ use InspiredMinds\ContaoUnifiedNewsAliases\Controller\FrontendModule\NewsReaderModuleController; $GLOBALS['TL_DCA']['tl_module']['palettes'][NewsReaderModuleController::TYPE] = $GLOBALS['TL_DCA']['tl_module']['palettes']['newsreader']; <file_sep>/src/ContaoManager/Plugin.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ namespace InspiredMinds\ContaoUnifiedNewsAliases\ContaoManager; use Contao\ManagerPlugin\Bundle\BundlePluginInterface; use Contao\ManagerPlugin\Bundle\Config\BundleConfig; use Contao\ManagerPlugin\Bundle\Parser\ParserInterface; use Contao\NewsBundle\ContaoNewsBundle; use InspiredMinds\ContaoUnifiedNewsAliases\ContaoUnifiedNewsAliasesBundle; class Plugin implements BundlePluginInterface { public function getBundles(ParserInterface $parser): array { return [ BundleConfig::create(ContaoUnifiedNewsAliasesBundle::class) ->setLoadAfter([ ContaoNewsBundle::class, 'changelanguage', ]), ]; } } <file_sep>/src/Resources/contao/languages/en/modules.php <?php declare(strict_types=1); /* * This file is part of the Contao Unified News Aliases extension. * * (c) inspiredminds * * @license LGPL-3.0-or-later */ use InspiredMinds\ContaoUnifiedNewsAliases\Controller\FrontendModule\NewsReaderModuleController; $GLOBALS['TL_LANG']['FMD'][NewsReaderModuleController::TYPE] = [ $GLOBALS['TL_LANG']['FMD']['newsreader'][0].' for unified aliases', 'This news reader allows to display news aliases via their unified (i.e. main) alias.', ];
cd792383e4c3c3918f77f1885d5b672677cec623
[ "Markdown", "PHP" ]
17
PHP
inspiredminds/contao-unified-news-aliases
3d55bef258c52dc8673dd98a4222a50be6d55694
2268101fbb71973f63c1bc782ca0dd05189c43fb
refs/heads/master
<file_sep>package com.glassdoor.test.intern.interfaces; import java.util.Map; public interface DaoOperations { void readDb(); void addNewRecord(Map<String, Object> databaseObject); } <file_sep>package com.glassdoor.test.intern.interfaces.impl; import com.glassdoor.test.intern.pymtProcDTO.UserObject; import com.glassdoor.test.intern.interfaces.DaoOperations; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; public class UserDatabase implements DaoOperations { Map<Integer, UserObject> users; public UserDatabase() { users = new HashMap<>(); this.readDb(); } @Override public void readDb() { try (BufferedReader br = new BufferedReader(new InputStreamReader( UserDatabase.class.getClassLoader().getResourceAsStream("user_database.txt")))) { String line; int lineNumber = 0; while ((line = br.readLine()) != null) { if (lineNumber > 0) { String[] splitLine = line.split("\\|"); UserObject userObj = new UserObject(splitLine); this.users.put(Integer.parseInt(splitLine[0]), userObj); } lineNumber += 1; } } catch (Exception e) { e.printStackTrace(); } } @Override public void addNewRecord(Map<String, Object> databaseObject) { } }<file_sep>package com.glassdoor.test.intern.interfaces.impl; import com.glassdoor.test.intern.pymtProcDTO.ErrorHandler; import com.glassdoor.test.intern.pymtProcDTO.IncomingRequest; import com.glassdoor.test.intern.pymtProcDTO.UserObject; import com.glassdoor.test.intern.interfaces.PaymentProcessor; public class IssuingBank implements PaymentProcessor { IncomingRequest incomingRequest; private boolean paymentStatus; public IssuingBank(IncomingRequest i) throws Exception { paymentStatus = false; incomingRequest = i; processPayment(); } @Override public void processPayment() throws Exception { chargeFee(); UserDatabase userDatabase = new UserDatabase(); // Check if user exists ? if (userDatabase.users.containsKey(incomingRequest.getUserId())) { UserObject user = userDatabase.users.get(incomingRequest.getUserId()); // If isCardPresentTransaction if (incomingRequest.isCardPresentTransaction()) { if (!incomingRequest.getPin().equals(user.getCardPin())) { throw new Exception(ErrorHandler.INCORRECTPIN); } } // Does the billing address and incomingRequest address correct if (user.getAddress().equals(incomingRequest.getBillingAddress())) { // Is there enough credit ? if (user.getAccountBalance() > incomingRequest.getAmount()) { // Was the card stolen ? if (!user.isCardStolen()) { // Location of transaction ? // Google maps integration if possible setPaymentStatus(); } else { throw new Exception(ErrorHandler.STOLENCARD); } } else { throw new Exception(ErrorHandler.INSUFFICIENTFUNDS); } } else { throw new Exception(ErrorHandler.ADDRESSMISMATCH); } } else { throw new Exception(ErrorHandler.CUSTOMERDOESNOTEXIST); } } @Override public boolean getPaymentStatus() { return paymentStatus; } @Override public void setPaymentStatus() {paymentStatus = true;} @Override public void chargeFee() { // Charge a 5% fee incomingRequest.setAmount(incomingRequest.getAmount() + (0.05F * incomingRequest.getOriginalAmount())); } } <file_sep>package com.glassdoor.test.intern.interfaces.impl; import com.glassdoor.test.intern.interfaces.DaoOperations; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class MerchantDatabase implements DaoOperations { public Set<String> merchants; public MerchantDatabase() { merchants = new HashSet<>(); readDb(); } @Override public void readDb() { try (BufferedReader br = new BufferedReader(new InputStreamReader( MerchantDatabase.class.getClassLoader().getResourceAsStream("merchant_database.txt")))) { String line; while ((line = br.readLine()) != null) { merchants.add(line); } } catch (Exception e) { e.printStackTrace(); } } @Override public void addNewRecord(Map<String, Object> databaseObject) { } } <file_sep>package com.glassdoor.test.intern.pymtProcDTO; public final class ErrorHandler { public static final String CARDNOTPRESENT = "Illegal Transaction request, this is a CardNotPresent Transaction"; public static final String MERCHANTDOESNOTEXIT = "Illegal Argument Exception, Merchant does not exist !"; public static final String INCORRECTPIN = "Illegal Transaction request, Pin is incorrect !"; public static final String STOLENCARD = "Illegal Transaction request, Card is Stolen !"; public static final String INSUFFICIENTFUNDS = "Illegal Transaction request, Insufficient Funds !"; public static final String ADDRESSMISMATCH = "Illegal Transaction request, Billing Address does not match !"; public static final String CUSTOMERDOESNOTEXIST = "Illegal Transaction request, User is not a customer of Issuing Bank !"; }<file_sep>### Online Processing Payment Application - **Author** : <NAME> #### Implementation Story - Online Payment Systems is something I was completely oblivious off before this project and researching through scores of sources of information eventually got me this [video](https://youtu.be/ZciY1No5-Rw). - The rough system design whiteboard after grasping the contents looked something like this `:dizzy_face:` ![](Documentation/Glassdoor_intern_SystemDesignWhiteBoard.jpg) - Here's a run down of the steps performed by this application: - The User initiates a request by passing in their name, address, amount, type of transaction, card scheme (Visa, Mastercard, Discover) etc. - The request is passed to the acquiring bank which holds the merchant's account. The acquiring bank checks if the merchant exists and then passes the request to the Card Scheme. - The Card Scheme is considered a blackbox for the purpose of this project and merely routes the data to the Issuing bank which holds the user's accounts. - The Issuing bank then runs a series of checks on the user. On verification that the transaction is feasible a success acknowledgement is backpropagated through the network to the user and the merchant. A service fee is charged at each of the payment processors. - The **isCardPresent** boolean is a very domain specific information for Online Payment Systems. It has nothing to do with the presence or absence of the card. If **isCardIsPresent** is **true** in the Payments world it is a chip and pin transaction while if it is **false** it indicates an online transaction like ones we do at ecommerce websites where we basically enter card information and that's that. #### UML Sequence Diagram ![](Documentation/Glassdoor_intern_UML_Sequence_Diagram.png) #### UML Class Diagram ![](Documentation/Glassdoor_intern_UML_Class_Diagram.png) #### Goal - My code is broken down into 4 main directories - Data Access Object files which basically consist of **UserDatabase.java** and **MerchantDatabase.java** - Payment Procedure Data Transfer Operations which are **IncomingRequest.java** and **UserObject.java**. - Payment Processor files which are **AcquiringBank.java**, **CardScheme.java** and **IssuingBank.java**. - Payment Runner file which is **PaymentApplication.java**. - I have used the **Factory Design Pattern** for this project which is evident from the ample usage of interfaces and objects. - There are two basic interfaces in the project which are **DaoOperations** and **PayProcessor** - Whenever possible class variables have been limited to private access modifiers to ensure **security** in the application and getters and setters are used to facilitate **accessibilty**. - Custom **Exceptions** are thrown to **validate** the data and caught in the application runner. A static final class **ErrorHandler.java** has been created to store the exception enumerations. - **Console based logging** has been achieved using the log42j library. #### Improvements - As a part of further improvements geospatial features of the transaction can be tracked to ensure prevention of fraudalent transactions. This can done by using the goolemaps java api and querying the distance between transaction location and user's billing address. A simple heuristic can then be employed to either validate or invalidate the transaction. - UserIDs could be generated randomly and passwords can be hashed using a hash function like md5 before storing to the database. - Concurrency can be ensured by making the class methods **synchronized** and spawning threads to pass multiple incomingRequests to the api. This will ensure that the methods are thread safe and concurrent in their execution. #### Testing - 9 test cases have been implemented to ensure correctness of code. - They simulate the following conditions: - Successful isCardPresent Transaction - Successful isCardNotPresent Transaction - Condition where **CustomerDoesNotExist** Exception is thrown - Condition where **CardNotPresent** Exception is thrown - Condition where **IncorrectPin** Exception is thrown - Condition where **AddressMismatch** Exception is thrown - Condition where **StolenCard** Exception is thrown - Condition where **InsufficientFunds** Exception is thrown - The exceptions listed above are in a **logical ordered hierarchy**. #### Acknowledgements: - **Glassdoor** - for boilerplate code. - **[<NAME>](https://www.linkedin.com/in/dennisjones2/)** - for the awesome YouTube video.
b510591834849a9a5d7d9700b7492b54a5ecbe0c
[ "Markdown", "Java" ]
6
Java
vishalseshagiri/OnlinePaymentSystem
6d17b779233246ed9f9ccf2e48443f1c5466ca7f
b052f6c049ca471ac723d7eb5afa849ddf5050fa
refs/heads/master
<file_sep>import {Component, OnInit} from '@angular/core'; import {AuthenticationService} from "../service/authentication.service"; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {ToastrService} from "ngx-toastr"; import {ActivatedRoute, Router} from "@angular/router"; import {PasswordMatchValidator} from "../guards/password-match.validator"; import {ResetPassword} from "../domain/ResetPassword"; import {User} from "../domain/User"; @Component({ selector: 'app-forgot-password', templateUrl: './forgot-password.component.html', styleUrls: ['./forgot-password.component.css'] }) export class ForgotPasswordComponent implements OnInit { private token: String; public changePasswordForm: FormGroup; public matcher: PasswordMatchValidator; public hidePassword1: Boolean; public hidePassword2: Boolean; constructor(private authService: AuthenticationService, private fb: FormBuilder, private toaster: ToastrService, private router: Router, private activatedRoute: ActivatedRoute) { } ngOnInit() { if (AuthenticationService.isUserLogin()) { this.router.navigate(['/statistics']); } this.activatedRoute.queryParams.subscribe(params => { this.token = params['token']; if (this.token == null) { this.goToLogin(); } }); this.hidePassword1 = true; this.hidePassword2 = true; this.matcher = new PasswordMatchValidator(); this.changePasswordForm = this.fb.group({ password: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(40)]], repeatPassword: [''] }, {validator: this.checkPasswords}); } onSubmitChangePassword() { let resetPassword: ResetPassword = new ResetPassword(); resetPassword.token = this.token; resetPassword.password = this.changePasswordForm.controls.password.value; this.authService.resetPassword(resetPassword).subscribe(message => { this.toaster.info(message.toString()); }) } goToLogin() { this.router.navigate(['/']); } checkPasswords(group: FormGroup) { let pass = group.controls.password.value; let confirmPass = group.controls.repeatPassword.value; return pass === confirmPass ? null : {notSame: true} } } <file_sep>package com.money.management.auth.domain; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import javax.validation.constraints.NotNull; import java.time.LocalDateTime; @Document(collection = "forgotPasswordToken") public class ForgotPasswordToken { @Id private String token; @NotNull private User user; @NotNull private LocalDateTime expireDate; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public LocalDateTime getExpireDate() { return expireDate; } public void setExpireDate(LocalDateTime expireDate) { this.expireDate = expireDate; } } <file_sep>buildscript { ext { springBootVersion = '2.1.1.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } plugins { id "org.sonarqube" version "2.6.1" } sonarqube { properties { property "sonar.projectName", "Money-Management" property "sonar.projectKey", "com.money.management" } } subprojects { apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'jacoco' apply plugin: 'org.springframework.boot' apply plugin: 'io.spring.dependency-management' group 'com.money.management' version '1.0-SNAPSHOT' sourceCompatibility = 1.11 targetCompatibility = 1.11 repositories { mavenCentral() maven { url "https://repo.spring.io/milestone" } } ext { springCloudVersion = 'Greenwich.RC2' } dependencies { compile('javax.xml.bind:jaxb-api:2.2.11') compile('com.sun.xml.bind:jaxb-core:2.2.11') compile('com.sun.xml.bind:jaxb-impl:2.2.11') compile('javax.activation:activation:1.1.1') testCompile('org.springframework.boot:spring-boot-starter-test') } dependencyManagement { imports { mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" } } }<file_sep>import {Component, OnInit} from '@angular/core'; import {AuthenticationService} from "../service/authentication.service"; import {Router} from "@angular/router"; import {StatisticsService} from "../service/statistics.service"; import {DataPoint} from "../domain/DataPoint"; import {DateFormatPipe} from "../pipe/date-format.pipe"; import {ItemMetric} from "../domain/ItemMetric"; @Component({ selector: 'app-statistics', templateUrl: './statistics.component.html', styleUrls: ['./statistics.component.css'] }) export class StatisticsComponent implements OnInit { public lineChartView: number[] = [900, 400]; public pieChartView: number[] = [600, 400]; public startDate: Date; public endDate: Date; public colorScheme = { domain: ['#5AA454', '#A10A28', '#C7B42C', '#AAAAAA'] }; public lineChartResults: any[] = []; public incomesPieChartResults: any[] = []; public expensePieChartResults: any[] = []; private datePoints: DataPoint[]; constructor(private authService: AuthenticationService, private router: Router, private statisticsService: StatisticsService, private dateFormatPipe: DateFormatPipe) { } ngOnInit() { this.statisticsService.getCurrentAccountStatistics().subscribe(results => { this.datePoints = results; this.populateCharts(results); }); this.initDates(); } public logout() { this.authService.logout(); location.reload(true); } public navigateToAccount() { this.router.navigate(['/account']); } public navigateToSettings() { this.router.navigate(['/settings']); } public onSelect(event) { this.datePoints.forEach(point => { let date = this.dateFormatPipe.transform(point.id.date); if (event.name == date) { this.populatePieCharts(point); return; } }) } public search() { this.statisticsService.getAccountStatisticsBetweenDates(this.startDate, this.endDate) .subscribe(results => { this.datePoints = results; this.populateCharts(results); }); } private populateCharts(results: DataPoint[]) { let incomeResults: any[] = []; let expensesResults: any[] = []; let incomesPieChartResults: Map<String, number> = new Map(); let expensesPieChartResults: Map<String, number> = new Map(); results.forEach(result => { this.extractLineChartData(result, incomeResults, expensesResults); this.extractPieChartData(incomesPieChartResults, result.incomes); this.extractPieChartData(expensesPieChartResults, result.expenses); }); this.lineChartResults = this.getLineChartData(incomeResults, expensesResults); this.incomesPieChartResults = this.getPieChartData(incomesPieChartResults); this.expensePieChartResults = this.getPieChartData(expensesPieChartResults); } private populatePieCharts(result: DataPoint) { let incomesPieChartResults: Map<String, number> = new Map(); let expensesPieChartResults: Map<String, number> = new Map(); this.extractPieChartData(incomesPieChartResults, result.incomes); this.extractPieChartData(expensesPieChartResults, result.expenses); this.incomesPieChartResults = this.getPieChartData(incomesPieChartResults); this.expensePieChartResults = this.getPieChartData(expensesPieChartResults); } private extractPieChartData(pieChartResults: Map<String, number>, items: Set<ItemMetric>) { items.forEach(income => { if (pieChartResults.has(income.title)) { let newAmount = pieChartResults.get(income.title) + Math.trunc(income.amount); pieChartResults.set(income.title, newAmount); } else { pieChartResults.set(income.title, Math.trunc(income.amount)); } }); } private extractLineChartData(result: DataPoint, incomeResults: any[], expensesResults: any[]) { let date = this.dateFormatPipe.transform(result.id.date); incomeResults.push({ name: date, value: result.statistics["INCOMES_AMOUNT"] }); expensesResults.push({ name: date, value: result.statistics["EXPENSES_AMOUNT"] }); } private getLineChartData(incomeResults: any[], expensesResults: any[]): any[] { return [ { name: 'Incomes', series: incomeResults }, { name: 'Expenses', series: expensesResults } ]; } private getPieChartData(pieChartResults: Map<String, number>): any[] { let pieChartResultsArray = this.convertPieChartMapToArray(pieChartResults); pieChartResultsArray.sort((a, b) => b.value - a.value); if (pieChartResultsArray.length > 4) { return this.shrinkPieChartArray(pieChartResultsArray); } else { return pieChartResultsArray; } } private convertPieChartMapToArray(pieChartResults: Map<String, number>): any[] { let pieChartResultsArray = []; pieChartResults.forEach((v, k) => { pieChartResultsArray.push({ "name": k, "value": v }); }); return pieChartResultsArray; } private shrinkPieChartArray(pieChartResultsArray: any[]): any[] { let others = { "name": "Others", "value": 0 }; pieChartResultsArray.slice(3, pieChartResultsArray.length).forEach(result => { others.value += result.value; }); let shrinkArray = pieChartResultsArray.slice(0, 3); shrinkArray.push(others); return shrinkArray; } private initDates() { let date = new Date(); this.startDate = new Date(date.getFullYear(), date.getMonth(), 1); this.endDate = new Date(date.getFullYear(), date.getMonth() + 1, 0); } } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AccountSectionComponent } from './account-section.component'; describe('AccountSectionComponent', () => { let component: AccountSectionComponent; let fixture: ComponentFixture<AccountSectionComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AccountSectionComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AccountSectionComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>export class DataPointId { account: String; date: Date; }<file_sep>import {Component, OnInit} from '@angular/core'; import {AuthenticationService} from "../service/authentication.service"; import {Router} from "@angular/router"; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {ToastrService} from "ngx-toastr"; import {PasswordMatchValidator} from "../guards/password-match.validator"; @Component({ selector: 'app-settings', templateUrl: './settings.component.html', styleUrls: ['./settings.component.css'] }) export class SettingsComponent implements OnInit { public changePasswordForm: FormGroup; public matcher: PasswordMatchValidator; public hidePassword1: Boolean; public hidePassword2: Boolean; constructor(private authService: AuthenticationService, private fb: FormBuilder, private toaster: ToastrService, private router: Router) { this.hidePassword1 = true; this.hidePassword2 = true; this.matcher = new PasswordMatchValidator(); this.changePasswordForm = this.fb.group({ password: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(40)]], repeatPassword: [''] }, {validator: this.checkPasswords}); } ngOnInit() { } onSubmitChangePassword() { this.authService.updatePassword(this.changePasswordForm.controls.password.value) .subscribe(() => this.toaster.success("Your password have been updated !")) } public logout() { this.authService.logout(); location.reload(true); } public navigateToAccount() { this.router.navigate(['/account']); } public navigateToStatistics() { this.router.navigate(['/statistics']); } checkPasswords(group: FormGroup) { let pass = group.controls.password.value; let confirmPass = group.controls.repeatPassword.value; return pass === confirmPass ? null : {notSame: true} } } <file_sep>import {Component, OnInit} from '@angular/core'; import {AuthenticationService} from "../service/authentication.service"; import {ActivatedRoute, Router} from "@angular/router"; @Component({ selector: 'app-verification', templateUrl: './verification.component.html', styleUrls: ['./verification.component.css'] }) export class VerificationComponent implements OnInit { public message: String; public isError: boolean; constructor(private authService: AuthenticationService, private router: Router, private activatedRoute: ActivatedRoute) { } ngOnInit() { if (AuthenticationService.isUserLogin()) { this.router.navigate(['/statistics']); } this.activatedRoute.queryParams.subscribe(params => { let token = params['token']; if (token == null) { this.router.navigate(['/']); } else { this.verifyEmail(token) } }); } private verifyEmail(token: String) { this.authService.verifyEmail(token).subscribe(response => { this.message = response.message; this.isError = false }, error => { this.message = error; this.isError = true; } ) } } <file_sep>import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {AppComponent} from './app.component'; import {BrowserAnimationsModule} from "@angular/platform-browser/animations"; import {FormsModule, ReactiveFormsModule} from "@angular/forms"; import {MaterialModule} from "./material.modules"; import {AppRouting} from "./app.routing"; import {AccountConnectionComponent} from "./front-page/account-section/account-connection/account-connection.component"; import {FrontPageComponent} from './front-page/front-page.component'; import {HTTP_INTERCEPTORS, HttpClientModule} from "@angular/common/http"; import {ToastrModule} from "ngx-toastr"; import {AccountComponent} from './account/account.component'; import {StatisticsComponent} from './statistics/statistics.component'; import {ItemDialogComponent} from './item-dialog/item-dialog.component'; import {NgxChartsModule} from "@swimlane/ngx-charts"; import {DateFormatPipe} from "./pipe/date-format.pipe"; import { SocialMediaConnectionComponent } from './front-page/account-section/social-media-connection/social-media-connection.component'; import { AccountSectionComponent } from './front-page/account-section/account-section.component'; import { AccountTroubleComponent } from './front-page/account-section/account-trouble/account-trouble.component'; import { ForgotPasswordComponent } from './forgot-password/forgot-password.component'; import { SettingsComponent } from './settings/settings.component'; import { VerificationComponent } from './verification/verification.component'; import {SanitizeUrlPipe} from "./pipe/sanitize-url.pipe"; import {ErrorInterceptor} from "./guards/error.interceptor"; import {JwtInterceptor} from "./guards/jwt.interceptor"; import { Oauth2Component } from './oauth2/oauth2.component'; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule, HttpClientModule, MaterialModule, ToastrModule.forRoot({ positionClass: 'toast-bottom-right', timeOut: 10000, extendedTimeOut: 10000 }), AppRouting, NgxChartsModule ], declarations: [ AppComponent, AccountConnectionComponent, FrontPageComponent, AccountComponent, StatisticsComponent, ItemDialogComponent, DateFormatPipe, SanitizeUrlPipe, SocialMediaConnectionComponent, AccountSectionComponent, AccountTroubleComponent, ForgotPasswordComponent, SettingsComponent, VerificationComponent, Oauth2Component ], bootstrap: [AppComponent], providers: [ { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, { provide: SanitizeUrlPipe }, { provide: DateFormatPipe } ], entryComponents: [ ItemDialogComponent ] }) export class AppModule { } <file_sep>package com.money.management.account.repository; import com.money.management.account.domain.Account; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface AccountRepository extends CrudRepository<Account, String> { Optional<Account> findByName(String name); } <file_sep>package com.money.management.auth.service; import com.money.management.auth.AuthApplication; import com.money.management.auth.domain.EmailType; import com.money.management.auth.service.impl.EmailServiceImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.core.env.Environment; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.MimeMessage; import java.util.Properties; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AuthApplication.class) public class EmailServiceTest { @InjectMocks private EmailServiceImpl emailService; @Mock private JavaMailSender mailSender; @Mock private Environment env; @Captor private ArgumentCaptor<MimeMessage> captor; @Before public void setup() { initMocks(this); when(mailSender.createMimeMessage()) .thenReturn(new MimeMessage(Session.getDefaultInstance(new Properties()))); } @Test public void shouldSendEmail() throws MessagingException { EmailType type = EmailType.VERIFICATION; String subject = "Subject"; when(env.getProperty(type.getSubject())).thenReturn(subject); when(env.getProperty(type.getUrl())).thenReturn("http://test.com?token="); when(env.getProperty(type.getText())).thenReturn("Test {0} test"); emailService.send(EmailType.VERIFICATION, "<EMAIL>", "12345"); verify(mailSender).send(captor.capture()); MimeMessage message = captor.getValue(); assertEquals(subject, message.getSubject()); } } <file_sep>rootProject.name = 'notification-service'<file_sep>package com.money.management.auth.domain; public enum AuthProvider { LOCAL, FACEBOOK, GOOGLE, TWITTER; public static AuthProvider getProvider(String value) { for (AuthProvider v : values()) if (v.name().equalsIgnoreCase(value)) return v; throw new IllegalArgumentException(); } } <file_sep>package com.money.management.statistics.util; import com.google.common.collect.ImmutableList; import com.money.management.statistics.domain.Account; import com.money.management.statistics.domain.Item; import com.money.management.statistics.domain.Saving; import java.util.Arrays; public class AccountUtil { private AccountUtil() { } public static Account getAccount(Saving saving, Item incomes, Item... expenses) { Account account = new Account(); account.setSaving(saving); account.setExpenses(Arrays.asList(expenses)); account.setIncomes(ImmutableList.of(incomes)); return account; } } <file_sep>import {ChangeDetectorRef, Component} from '@angular/core'; import {animate, state, style, transition, trigger} from "@angular/animations"; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {AccountSection} from "../account-section"; import {AuthenticationService} from "../../../service/authentication.service"; import {ToastrService} from "ngx-toastr"; @Component({ selector: 'app-account-trouble', templateUrl: './account-trouble.component.html', styleUrls: ['./account-trouble.component.css'], animations: [ trigger('flipState', [ state('active', style({ transform: 'rotateY(179.9deg)' })), state('inactive', style({ transform: 'rotateY(0)' })), transition('active => inactive', animate('1000ms ease-out')), transition('inactive => active', animate('1000ms ease-in')) ]), trigger('showLogin', [ state('true', style({opacity: 1, transform: 'translateY(0%)'})), state('false', style({opacity: 0, transform: 'translateY(100%)'})), transition('false => true', [animate('1s 0.5s ease-in')]) ]), ] }) export class AccountTroubleComponent extends AccountSection { public flip: String; public forgotPassword: FormGroup; public resendEmail: FormGroup; constructor(private formBuilder: FormBuilder, private authService: AuthenticationService, toaster: ToastrService, cdr: ChangeDetectorRef) { super(cdr, toaster); this.flip = 'inactive'; this.forgotPassword = this.formBuilder.group({ email: ['', [Validators.required, Validators.email]] }); this.resendEmail = this.formBuilder.group({ email: ['', [Validators.required, Validators.email]] }); } onForgotPasswordSubmit() { let email = this.forgotPassword.controls.email.value; this.authService.forgotPassword(email).subscribe(result => this.displaySuccessMessage(result.message), error => this.displayErrorMessage(error.error.message)); } onResendEmailSubmit() { let email = this.resendEmail.controls.email.value; this.authService.resendVerificationEmail(email).subscribe(result => this.displaySuccessMessage(result.message), error => this.displayErrorMessage(error.error.message)); } toggleFlip() { this.flip = (this.flip === 'inactive') ? 'active' : 'inactive'; } } <file_sep>package com.money.management.account.service.security; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails; public class SecurityHolderOAuth2AccessToken extends DefaultOAuth2AccessToken { private String value; public SecurityHolderOAuth2AccessToken() { super(""); } @Override public String getValue() { if (value == null || value.isEmpty()) { value = getAccessToken(); } return value; } private String getAccessToken() { OAuth2Authentication authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication(); Object details = authentication.getDetails(); if (details instanceof OAuth2AuthenticationDetails) { OAuth2AuthenticationDetails oauthDetails = (OAuth2AuthenticationDetails) details; return oauthDetails.getTokenValue(); } return null; } } <file_sep>package com.money.management.account.service; import com.money.management.account.exception.BadRequestException; import com.money.management.account.repository.AccountRepository; import com.money.management.account.client.StatisticsServiceClient; import com.money.management.account.domain.Account; import com.money.management.account.domain.Currency; import com.money.management.account.domain.Saving; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.security.Principal; import java.util.Date; import java.util.Optional; @Service public class AccountServiceImpl implements AccountService { private final Logger log = LoggerFactory.getLogger(getClass()); private StatisticsServiceClient statisticsClient; private AccountRepository repository; @Autowired public AccountServiceImpl(StatisticsServiceClient statisticsClient, AccountRepository repository) { this.statisticsClient = statisticsClient; this.repository = repository; } @Override public Account findByName(String accountName) { Optional<Account> account = repository.findByName(accountName); return account.orElseThrow(() -> new BadRequestException("The account " + accountName + " doesn't exist !")); } @Override public Account findByName(Principal principal) { Optional<Account> account = repository.findByName(principal.getName()); return account.orElse(createAccount(principal.getName())); } @Override public void saveChanges(String name, Account update) { Optional<Account> optionalAccount = repository.findByName(name); Account account = optionalAccount.orElseThrow(() -> new BadRequestException("Can't find account with name " + name)); updateAccount(account, update); repository.save(account); log.debug("Account {} changes has been saved", name); statisticsClient.updateStatistics(name, account); } private Saving getDefaultSaving() { Saving saving = new Saving(); saving.setAmount(new BigDecimal(0)); saving.setCurrency(Currency.getDefault()); saving.setInterest(new BigDecimal(0)); saving.setDeposit(false); saving.setCapitalization(false); return saving; } private Account createAccount(String userName) { Account account = getAccount(userName); repository.save(account); log.info("New account has been created: {}", account.getName()); return account; } private Account getAccount(String userName) { Account account = new Account(); account.setName(userName); account.setLastSeen(new Date()); account.setSaving(getDefaultSaving()); return account; } private void updateAccount(Account account, Account update) { account.setIncomes(update.getIncomes()); account.setExpenses(update.getExpenses()); account.setSaving(update.getSaving()); account.setNote(update.getNote()); account.setLastSeen(new Date()); } } <file_sep>package com.money.management.auth.repository; import com.money.management.auth.domain.VerificationToken; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface VerificationTokenRepository extends CrudRepository<VerificationToken, String> { VerificationToken findByToken(String token); VerificationToken findByUserUsername(String username); } <file_sep>package com.money.management.auth.security; import org.springframework.security.core.Authentication; public interface TokenProviderService { String createToken(Authentication authentication); String getUserNameFromToken(String token); boolean validateToken(String authToken); } <file_sep>package com.money.management.auth.repository; import com.money.management.auth.AuthApplication; import com.money.management.auth.domain.ForgotPasswordToken; import com.money.management.auth.util.UserUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.time.LocalDateTime; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AuthApplication.class) public class ForgotPasswordTokenRepositoryTest { @Autowired private ForgotPasswordTokenRepository repository; @Test public void shouldSaveAndFindForgotPasswordById() { ForgotPasswordToken saved = new ForgotPasswordToken(); saved.setToken("<PASSWORD>"); saved.setExpireDate(LocalDateTime.now()); saved.setUser(UserUtil.getUser()); repository.save(saved); ForgotPasswordToken found = repository.findById(saved.getToken()).get(); assertThat(saved, is(saved)); } } <file_sep>package com.money.management.auth.security; import com.money.management.auth.AuthApplication; import com.money.management.auth.config.AppProperties; import com.money.management.auth.domain.User; import com.money.management.auth.security.impl.TokenProviderServiceImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AuthApplication.class) public class TokenProviderServiceImplTest { @InjectMocks private TokenProviderServiceImpl service; @Mock private AppProperties appProperties; @Before public void setup() { initMocks(this); } @Test public void shouldReturnNewToken() { User user = new User(); user.setUsername("test"); TestingAuthenticationToken authenticationToken = new TestingAuthenticationToken(user, null); when(appProperties.getAuth()).thenReturn(getAuth()); assertNotNull(service.createToken(authenticationToken)); } @Test public void shouldNotValidateToken() { when(appProperties.getAuth()).thenReturn(getAuth()); assertFalse(service.validateToken("")); } private AppProperties.Auth getAuth() { AppProperties.Auth auth = new AppProperties.Auth(); auth.setTokenExpirationMsec(12345L); auth.setTokenSecret("12345"); return auth; } } <file_sep>package com.money.management.auth.service; import com.money.management.auth.domain.EmailType; import javax.mail.MessagingException; public interface EmailService { void send(EmailType type, String email, String token) throws MessagingException; } <file_sep>package com.money.management.statistics.repository; import com.money.management.statistics.domain.timeseries.DataPoint; import com.money.management.statistics.domain.timeseries.DataPointId; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; @Repository public interface DataPointRepository extends CrudRepository<DataPoint, DataPointId> { List<DataPoint> findByIdAccount(String account); @Query("{ $and: [{'id.account': { $eq: ?0 }}, {'id.date': {$gte: ?1, $lte: ?2}}]}") List<DataPoint> findByIdAccountBetweenDates(String account, Date beginDate, Date endDate); } <file_sep>import {Component, OnInit} from '@angular/core'; import {AuthenticationService} from "../service/authentication.service"; import {ActivatedRoute, Router} from "@angular/router"; import {ToastrService} from "ngx-toastr"; @Component({ selector: 'app-oauth2', templateUrl: './oauth2.component.html', styleUrls: ['./oauth2.component.css'] }) export class Oauth2Component implements OnInit { constructor(private router: Router, private activatedRoute: ActivatedRoute, private authService: AuthenticationService, public toaster: ToastrService) { } ngOnInit() { if (AuthenticationService.isUserLogin()) { this.router.navigate(['/statistics']); } this.activatedRoute.queryParams.subscribe(params => { let token = params['token']; let error = params['error']; this.treatsError(error); this.treatsLogin(token); }); } private treatsLogin(token: String) { if (token == null) { this.router.navigate(['/']); } else { this.authService.saveCredentials(token, '', false) } } private treatsError(message: String) { if (message != null) { message.replace('%20', ' '); message.replace('%27', '\''); this.toaster.error(message.toString(), 'Error'); this.router.navigate(['/']); } } } <file_sep>import {Injectable} from '@angular/core'; @Injectable({ providedIn: 'root' }) export class IconService { constructor() { } public static getExpenseIcons(): String[] { return ['car', 'clothes', 'gift', 'house', 'learning', 'grocery', 'vacation', 'restaurant', 'gym', 'phone', 'repair']; } public static getIncomeIcons(): String[] { return ['salary', 'interest', 'sell']; } public getIcon(name: String): String { return "../../assets/img/" + name + ".svg" } } <file_sep>import {Injectable} from '@angular/core'; import {HttpClient, HttpHeaders} from "@angular/common/http"; import {AuthenticationService} from "./authentication.service"; import {DataPoint} from "../domain/DataPoint"; import {Observable} from "rxjs"; @Injectable({ providedIn: 'root' }) export class StatisticsService { private currentAccountStatistics = 'api/statistics/current'; private betweenAccountStatistics = 'api/statistics/between'; constructor(private http: HttpClient) { } public getCurrentAccountStatistics(): Observable<DataPoint[]> { let token = AuthenticationService.getOauthToken(); let headers = new HttpHeaders({'Authorization': 'Bearer ' + token}); let options = { headers: headers }; return this.http.get<DataPoint[]>(this.currentAccountStatistics, options); } public getAccountStatisticsBetweenDates(startDate: Date, endDate: Date): Observable<DataPoint[]> { let token = AuthenticationService.getOauthToken(); let headers = new HttpHeaders({'Authorization': 'Bearer ' + token}); let options = { headers: headers }; let url = this.betweenAccountStatistics + "?"; url += "beginDate=" + startDate.getFullYear() + "-" + (startDate.getMonth() + 1) + "-" + (startDate.getDay() + 1); url += "&endDate=" + endDate.getFullYear() + "-" + (endDate.getMonth() + 1) + "-" + (endDate.getDay() + 1); return this.http.get<DataPoint[]>(url, options); } } <file_sep>package com.money.management.account.client; import com.money.management.account.domain.Account; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @FeignClient(name = "statistics-service") public interface StatisticsServiceClient { @RequestMapping(method = RequestMethod.PUT, value = "/statistics/find", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) void updateStatistics(@RequestParam("name") String accountName, Account account); } <file_sep>FROM openjdk:11-jdk ADD ./build/libs/auth-service-1.0-SNAPSHOT.jar /app/ ENTRYPOINT ["java","-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005","-jar","/app/auth-service-1.0-SNAPSHOT.jar"] EXPOSE 5000 5005<file_sep>package com.money.management.auth.service.impl; import com.money.management.auth.domain.AuthProvider; import com.money.management.auth.domain.ForgotPasswordToken; import com.money.management.auth.exception.BadRequestException; import com.money.management.auth.payload.ResetPasswordRequest; import com.money.management.auth.domain.User; import com.money.management.auth.listener.event.OnForgotPasswordCompleteEvent; import com.money.management.auth.repository.ForgotPasswordTokenRepository; import com.money.management.auth.repository.UserRepository; import com.money.management.auth.service.ForgotPasswordService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.util.Optional; import java.util.UUID; @Service public class ForgotPasswordServiceImpl implements ForgotPasswordService { private UserRepository userRepository; private ApplicationEventPublisher eventPublisher; private ForgotPasswordTokenRepository repository; private PasswordEncoder encoder; @Autowired public ForgotPasswordServiceImpl(UserRepository userRepository, ApplicationEventPublisher eventPublisher, PasswordEncoder encoder, ForgotPasswordTokenRepository repository) { this.userRepository = userRepository; this.eventPublisher = eventPublisher; this.repository = repository; this.encoder = encoder; } @Override public void sendEmail(String email) { User user = userRepository.findUsersByUsername(email) .filter(u -> AuthProvider.LOCAL.equals(u.getProvider())) .orElseThrow(() -> new BadRequestException("User doesn't exist, please register !")); if (!user.isEnabled()) { throw new BadRequestException("The user isn't enabled !"); } eventPublisher.publishEvent(new OnForgotPasswordCompleteEvent(user)); } @Override public ForgotPasswordToken createToken(User user) { ForgotPasswordToken token = new ForgotPasswordToken(); token.setUser(user); token.setToken(UUID.randomUUID().toString()); token.setExpireDate(LocalDateTime.now().plusDays(1)); repository.save(token); return token; } @Override public void resetPassword(ResetPasswordRequest resetPasswordRequest) { Optional<ForgotPasswordToken> optional = repository.findById(resetPasswordRequest.getToken()); if (optional.isEmpty()) { throw new BadRequestException("The token is invalid !"); } ForgotPasswordToken token = optional.get(); if (token.getExpireDate().isBefore(LocalDateTime.now())) { throw new BadRequestException("Forgot password toke has expired !"); } updateUserPassword(token.getUser(), resetPasswordRequest.getPassword()); } private void updateUserPassword(User user, String password) { user.setPassword(encoder.encode(password)); userRepository.save(user); } } <file_sep>package com.money.management.statistics.service; import com.google.common.collect.ImmutableMap; import com.money.management.statistics.StatisticsApplication; import com.money.management.statistics.client.ExchangeRatesClient; import com.money.management.statistics.domain.Currency; import com.money.management.statistics.domain.ExchangeRatesContainer; import com.money.management.statistics.service.impl.ExchangeRatesServiceImpl; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; import static org.mockito.MockitoAnnotations.initMocks; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = StatisticsApplication.class) public class ExchangeRatesServiceImplTest { @InjectMocks private ExchangeRatesServiceImpl ratesService; @Mock private ExchangeRatesClient client; @Before public void setup() { initMocks(this); } @Test public void shouldReturnCurrentRatesWhenContainerIsEmptySoFar() { ExchangeRatesContainer container = getExchangeRatesContainer(); when(client.getRates()).thenReturn(container); Map<Currency, BigDecimal> result = ratesService.getCurrentRates(); verify(client, times(1)).getRates(); assertEquals(container.getRates().get(Currency.EUR.name()), result.get(Currency.EUR)); assertEquals(BigDecimal.ONE, result.get(Currency.USD)); } @Test public void shouldNotRequestRatesWhenTodayContainerAlreadyExists() { when(client.getRates()).thenReturn(getExchangeRatesContainer()); ratesService.getCurrentRates(); verify(client, times(1)).getRates(); } @Test public void shouldConvertCurrency() { when(client.getRates()).thenReturn(getExchangeRatesContainer()); BigDecimal amount = new BigDecimal(100); BigDecimal expectedConversion = new BigDecimal("80.00"); BigDecimal result = ratesService.convert(Currency.USD, Currency.EUR, amount); assertEquals(0, expectedConversion.compareTo(result)); } @Test(expected = IllegalArgumentException.class) public void shouldFailToConvertWhenAmountIsNull() { ratesService.convert(Currency.EUR, Currency.USD, null); } private ExchangeRatesContainer getExchangeRatesContainer() { ExchangeRatesContainer container = new ExchangeRatesContainer(); container.setRates(ImmutableMap.of( Currency.EUR.name(), new BigDecimal("0.8"), Currency.USD.name(), new BigDecimal("80") )); container.setDate(LocalDate.now()); container.setBase(Currency.EUR); return container; } }<file_sep>export class Saving { amount: number; currency: String; interest: number; deposit: boolean; capitalization: boolean; }<file_sep>rootProject.name = 'account-service'<file_sep>import {RouterModule, Routes} from '@angular/router'; import {ModuleWithProviders} from '@angular/core'; import {FrontPageComponent} from "./front-page/front-page.component"; import {AccountComponent} from "./account/account.component"; import {StatisticsComponent} from "./statistics/statistics.component"; import {ForgotPasswordComponent} from "./forgot-password/forgot-password.component"; import {SettingsComponent} from "./settings/settings.component"; import {VerificationComponent} from "./verification/verification.component"; import {AuthGuard} from "./guards/auth.guard"; import {Oauth2Component} from "./oauth2/oauth2.component"; const APP_ROUTES: Routes = [ {path: '', component: FrontPageComponent}, {path: 'account', component: AccountComponent, canActivate: [AuthGuard]}, {path: 'statistics', component: StatisticsComponent, canActivate: [AuthGuard]}, {path: 'settings', component: SettingsComponent, canActivate: [AuthGuard]}, {path: 'reset-password', component: ForgotPasswordComponent}, {path: 'verification', component: VerificationComponent}, {path: 'oauth2/redirect', component: Oauth2Component}, {path: '**', redirectTo: '/statistics', pathMatch: 'full'} ]; export const AppRouting: ModuleWithProviders = RouterModule.forRoot(APP_ROUTES); <file_sep>import {Component, Inject, OnInit} from '@angular/core'; import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material"; import {Item} from "../domain/Item"; import {AuthenticationService} from "../service/authentication.service"; import {IconService} from "../service/icon.service"; @Component({ selector: 'app-item-dialog', templateUrl: './item-dialog.component.html', styleUrls: ['./item-dialog.component.css'] }) export class ItemDialogComponent implements OnInit { public title: String = ""; public icons: String[] = []; constructor( private authService: AuthenticationService, public iconService: IconService, public dialogRef: MatDialogRef<ItemDialogComponent>, @Inject(MAT_DIALOG_DATA) public item: Item) { } ngOnInit() { if (this.item == null) { this.initItem() } } onCloseClick(): void { this.dialogRef.close(null); } onAddClick() { this.dialogRef.close(this.item); } private initItem() { this.item = new Item(); this.item.currency = 'EUR'; this.item.period = 'MONTH'; this.item.amount = '0'; this.item.icon = ''; } } <file_sep>rootProject.name = 'money-management' include 'registry' include 'gateway' include 'auth-service' include 'account-service' include 'statistics-service' include 'notification-service'<file_sep>package com.money.management.auth.security.impl; import com.money.management.auth.payload.LoginRequest; import com.money.management.auth.security.AuthenticationManagerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @Service public class AuthenticationManagerServiceImpl implements AuthenticationManagerService { private AuthenticationManager authenticationManager; @Autowired public AuthenticationManagerServiceImpl(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Override public Authentication authenticate(LoginRequest loginRequest) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken( loginRequest.getEmail(), loginRequest.getPassword() ); Authentication authentication = authenticationManager.authenticate(authenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); return authentication; } } <file_sep>package com.money.management.auth.service; import com.money.management.auth.AuthApplication; import com.money.management.auth.repository.UserRepository; import com.money.management.auth.domain.User; import com.money.management.auth.service.impl.UserServiceImpl; import com.money.management.auth.util.UserUtil; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationEventPublisher; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Optional; import static org.mockito.Mockito.*; import static org.mockito.MockitoAnnotations.initMocks; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AuthApplication.class) public class UserServiceTest { @InjectMocks private UserServiceImpl userService; @Mock private PasswordEncoder encoder; @Mock private UserRepository repository; @Mock private ApplicationEventPublisher eventPublisher; @Before public void setup() { initMocks(this); } @Test public void shouldUpdateUserPassword() { User user = UserUtil.getUser(); when(repository.findUsersByUsername(user.getUsername())).thenReturn(Optional.of(user)); userService.changePassword(user.getUsername(), "<PASSWORD>"); verify(repository, times(1)).save(user); } } <file_sep>import { FormGroup } from '@angular/forms'; export function PasswordComplexity(controlName: string) { return (formGroup: FormGroup) => { const control = formGroup.controls[controlName]; if (control.errors && !control.errors.passwordComplexity) { // return if another validator has already found an error on the matchingControl return; } if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/.test(control.value)) { control.setErrors({ passwordComplexity: true }); } else { control.setErrors(null); } } } <file_sep>package com.money.management.notification.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableMap; import com.money.management.notification.domain.NotificationType; import com.money.management.notification.NotificationApplication; import com.money.management.notification.domain.Recipient; import com.money.management.notification.service.RecipientService; import com.money.management.notification.util.NotificationUtil; import com.money.management.notification.util.RecipientUtil; import com.sun.security.auth.UserPrincipal; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = NotificationApplication.class) @WebAppConfiguration public class RecipientControllerTest { private static final ObjectMapper mapper = new ObjectMapper(); @InjectMocks private RecipientController recipientController; @Mock private RecipientService recipientService; private MockMvc mockMvc; @Before public void setup() { initMocks(this); this.mockMvc = MockMvcBuilders.standaloneSetup(recipientController).build(); } @Test public void shouldSaveCurrentRecipientSettings() throws Exception { Recipient recipient = getStubRecipient(); String json = mapper.writeValueAsString(recipient); mockMvc.perform(put("/recipients/current").principal(new UserPrincipal(recipient.getAccountName())). contentType(MediaType.APPLICATION_JSON).content(json)) .andExpect(status().isOk()); } @Test public void shouldGetCurrentRecipientSettings() throws Exception { Recipient recipient = getStubRecipient(); when(recipientService.findByAccountName(recipient.getAccountName())).thenReturn(recipient); mockMvc.perform(get("/recipients/current").principal(new UserPrincipal(recipient.getAccountName()))) .andExpect(jsonPath("$.accountName").value(recipient.getAccountName())) .andExpect(status().isOk()); } private Recipient getStubRecipient() { return RecipientUtil.getRecipient(ImmutableMap.of( NotificationType.BACKUP, NotificationUtil.getBackup(), NotificationType.REMIND, NotificationUtil.getRemind(null) )); } }<file_sep>package com.money.management.auth.security; import com.money.management.auth.config.AppProperties; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.OAuth2Request; import org.springframework.stereotype.Component; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; @Component public class JwtAccessTokenConverter extends org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter { private AppProperties appProperties; private UserDetailsService userDetailsService; @Autowired public JwtAccessTokenConverter(AppProperties appProperties, UserDetailsService userDetailsService) { this.appProperties = appProperties; this.userDetailsService = userDetailsService; } @Override public Map<String, Object> decode(String token) { Claims claims = Jwts.parser() .setSigningKey(appProperties.getAuth().getTokenSecret()) .parseClaimsJws(token) .getBody(); Map<String, Object> map = new HashMap<>(); map.put(Claims.ID, claims.getId()); map.put(Claims.SUBJECT, claims.getSubject()); map.put(Claims.AUDIENCE, claims.getAudience()); map.put(Claims.EXPIRATION, claims.getExpiration()); map.put(Claims.ISSUED_AT, claims.getIssuedAt()); map.put(Claims.ISSUER, claims.getIssuer()); map.put(Claims.NOT_BEFORE, claims.getNotBefore()); return map; } @Override public OAuth2Authentication extractAuthentication(Map<String, ?> map) { String userName = (String) map.get(Claims.SUBJECT); UserDetails userDetails = userDetailsService.loadUserByUsername(userName); UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); OAuth2Request request = new OAuth2Request(null, null, null, true, Collections.emptySet(), null, null, null, null); return new OAuth2Authentication(request, user); } @Override public boolean isRefreshToken(OAuth2AccessToken token) { return false; } @Override public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map) { DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(value); Map<String, Object> info = new HashMap<>(map); info.remove(EXP); info.remove(AUD); if (map.containsKey(EXP)) { token.setExpiration((Date) map.get(EXP)); } token.setScope(Collections.emptySet()); token.setAdditionalInformation(info); return token; } } <file_sep>package com.money.management.account.service; import com.money.management.account.domain.Account; import java.security.Principal; public interface AccountService { Account findByName(String accountName); Account findByName(Principal principal); void saveChanges(String name, Account update); } <file_sep>export class Item { title: String; amount: String; currency: String; period: String; icon: String; }<file_sep>import {Item} from "./Item"; import {Saving} from "./Saving"; export class Account { name: String; lastSeen: Date; incomes: Item[]; expenses: Item[]; saving: Saving; note: String; }<file_sep>import {ChangeDetectorRef, Component} from '@angular/core'; import {animate, state, style, transition, trigger} from '@angular/animations'; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; import {AuthenticationService} from "../../../service/authentication.service"; import {ToastrService} from "ngx-toastr"; import {AccountSection} from "../account-section"; import {PasswordMatchValidator} from "../../../guards/password-match.validator"; import {Router} from "@angular/router"; import {AuthRequest} from "../../../domain/AuthRequest"; @Component({ selector: 'app-account-connection', templateUrl: './account-connection.component.html', styleUrls: ['./account-connection.component.css'], animations: [ trigger('flipState', [ state('active', style({ transform: 'rotateY(179.9deg)' })), state('inactive', style({ transform: 'rotateY(0)' })), transition('active => inactive', animate('1000ms ease-out')), transition('inactive => active', animate('1000ms ease-in')) ]), trigger('showLogin', [ state('true', style({opacity: 1, transform: 'translateY(0%)'})), state('false', style({opacity: 0, transform: 'translateY(100%)'})), transition('false => true', [animate('1s 0.5s ease-in')]) ]) ] }) export class AccountConnectionComponent extends AccountSection { public hidePassword1: Boolean; public hidePassword2: Boolean; public hidePassword3: Boolean; public flip: String; public loginForm: FormGroup; public createAccountForm: FormGroup; public matcher: PasswordMatchValidator; constructor(private fb: FormBuilder, private authService: AuthenticationService, private router: Router, toaster: ToastrService, cdr: ChangeDetectorRef) { super(cdr, toaster); this.checkIfUserISLogin(); this.initVariables(); this.initForms(); } onSubmitCreateAccount() { let authRequest = new AuthRequest(); authRequest.email = this.createAccountForm.controls.email.value; authRequest.password = this.createAccountForm.controls.password.value; this.authService.createUser(authRequest).subscribe( response => this.displaySuccessMessage(response.message), error => this.displayErrorMessage(error.error.message)); } onSubmitLogin() { let authRequest = new AuthRequest(); authRequest.email = this.loginForm.controls.email.value; authRequest.password = this.loginForm.controls.password.value; console.log(this.loginForm.controls.rememberMe.value); this.authService.obtainAccessToken(authRequest).subscribe( data => this.authService.saveCredentials(data.accessToken, authRequest.email, this.loginForm.controls.rememberMe.value)) } toggleFlip() { this.flip = (this.flip === 'inactive') ? 'active' : 'inactive'; } checkPasswords(group: FormGroup) { let pass = group.controls.password.value; let confirmPass = group.controls.repeatPassword.value; return pass === confirmPass ? null : {notSame: true} } private initVariables() { this.flip = 'inactive'; this.hidePassword1 = true; this.hidePassword2 = true; this.hidePassword3 = true; this.matcher = new PasswordMatchValidator(); } private initForms() { this.loginForm = this.fb.group({ email: ['', [Validators.required, Validators.email, Validators.minLength(3), Validators.maxLength(64)]], password: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(40)]], rememberMe: [false] }); this.createAccountForm = this.fb.group({ email: ['', [Validators.required, Validators.email, Validators.minLength(3), Validators.maxLength(64)]], password: ['', [Validators.required, Validators.minLength(6), Validators.maxLength(40)]], repeatPassword: [''] }, {validator: this.checkPasswords}); } private checkIfUserISLogin() { if (AuthenticationService.isUserLogin()) { this.router.navigate(['/statistics']) } } }<file_sep>package com.money.management.account.domain; public enum Currency { USD, EUR; public static Currency getDefault() { return EUR; } } <file_sep>import {AfterViewInit, ChangeDetectorRef, HostListener, OnInit} from "@angular/core"; import {ToastrService} from "ngx-toastr"; export class AccountSection implements OnInit, AfterViewInit { public showSection: Boolean = false; private windowHeight: number; private scrollPosition: number; constructor(private cdr: ChangeDetectorRef, public toaster: ToastrService) { } ngOnInit() { this.windowHeight = window.innerHeight; } ngAfterViewInit(): void { this.scrollPosition = window.pageYOffset; this.checkShowSection(); this.cdr.detectChanges(); } @HostListener('window:scroll', ['$event']) checkScroll() { this.scrollPosition = window.pageYOffset; this.checkShowSection(); } @HostListener('window:resize', ['$event']) onResize() { this.scrollPosition = window.pageYOffset; this.windowHeight = window.innerHeight; this.checkShowSection(); } displaySuccessMessage(message: string) { this.toaster.success(message, 'Success'); } displayErrorMessage(message: string) { this.toaster.error(message, 'Error'); } private checkShowSection() { if (this.windowHeight * 4.5 <= this.scrollPosition) { this.showSection = true; } } } <file_sep>package com.money.management.auth.listener; import com.money.management.auth.AuthApplication; import com.money.management.auth.domain.EmailType; import com.money.management.auth.domain.User; import com.money.management.auth.domain.VerificationToken; import com.money.management.auth.listener.event.OnResendVerificationEmailCompleteEvent; import com.money.management.auth.service.EmailService; import com.money.management.auth.util.UserUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.mail.MessagingException; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AuthApplication.class) public class ResendVerificationEmailListenerTest { @InjectMocks private ResendVerificationEmailListener registrationListener; @Mock private EmailService emailService; @Test public void shouldSendEmail() throws MessagingException { User user = UserUtil.getUser(); VerificationToken token = new VerificationToken(); token.setUser(user); token.setToken("<PASSWORD>"); OnResendVerificationEmailCompleteEvent event = new OnResendVerificationEmailCompleteEvent(token); registrationListener.onApplicationEvent(event); verify(emailService, times(1)).send(EmailType.VERIFICATION, user.getUsername(), token.getToken()); } } <file_sep>FROM openjdk:11-jdk ADD ./build/libs/statistics-service-1.0-SNAPSHOT.jar /app/ ENTRYPOINT ["java", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:7005", "-jar", "/app/statistics-service-1.0-SNAPSHOT.jar"] EXPOSE 7000 7005<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AccountConnectionComponent } from './account-connection.component'; describe('LoginComponent', () => { let component: AccountConnectionComponent; let fixture: ComponentFixture<AccountConnectionComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AccountConnectionComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AccountConnectionComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>package com.money.management.auth.domain; import org.hibernate.validator.constraints.Length; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.oauth2.core.user.OAuth2User; import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import java.util.Collection; import java.util.Map; @Document(collection = "users") public class User implements OAuth2User, UserDetails { @Id @Email @Length(min = 3, max = 64) private String username; @NotNull @Length(min = 6, max = 40) private String password; @NotNull private Boolean enabled; @NotNull private Collection<? extends GrantedAuthority> authorities; private Map<String, Object> attributes; @NotNull private AuthProvider provider; @NotNull private String providerId; @Override public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } public void setAuthorities(Collection<? extends GrantedAuthority> authorities) { this.authorities = authorities; } @Override public Map<String, Object> getAttributes() { return attributes; } public void setAttributes(Map<String, Object> attributes) { this.attributes = attributes; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public AuthProvider getProvider() { return provider; } public void setProvider(AuthProvider provider) { this.provider = provider; } public String getProviderId() { return providerId; } public void setProviderId(String providerId) { this.providerId = providerId; } @Override public String getName() { return username; } } <file_sep>$(document).ready(function () { //------------------------------------// //Navbar// //------------------------------------// var menu = $('.navbar'); $(window).bind('scroll', function (e) { if ($(window).scrollTop() > 140) { if (!menu.hasClass('open')) { menu.addClass('open'); } } else { if (menu.hasClass('open')) { menu.removeClass('open'); } } }); //------------------------------------// //Scroll To// //------------------------------------// $(".scroll").click(function (event) { event.preventDefault(); $('html,body').animate({scrollTop: $(this.hash).offset().top}, 800); }); }); <file_sep>package com.money.management.auth.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.money.management.auth.AuthApplication; import com.money.management.auth.payload.LoginRequest; import com.money.management.auth.payload.ResetPasswordRequest; import com.money.management.auth.payload.SignUpRequest; import com.money.management.auth.security.AuthenticationManagerService; import com.money.management.auth.security.TokenProviderService; import com.money.management.auth.service.ForgotPasswordService; import com.money.management.auth.service.UserService; import com.money.management.auth.service.VerificationTokenService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AuthApplication.class) @WebAppConfiguration public class AuthControllerTest { private static final String MESSAGE = "TEST"; private static final String EMAIL = "<EMAIL>"; private static final ObjectMapper mapper = new ObjectMapper(); @InjectMocks private AuthController authController; @Mock private VerificationTokenService verificationTokenService; @Mock private AuthenticationManagerService authenticationManagerService; @Mock private TokenProviderService tokenProviderService; @Mock private UserService userService; @Mock private ForgotPasswordService forgotPasswordService; private MockMvc mockMvc; @Before public void setup() { initMocks(this); this.mockMvc = MockMvcBuilders.standaloneSetup(authController).build(); } @Test public void shouldLoginUser() throws Exception { LoginRequest loginRequest = new LoginRequest(); loginRequest.setEmail(EMAIL); loginRequest.setPassword("<PASSWORD>"); when(authenticationManagerService.authenticate(loginRequest)).thenReturn(null); when(tokenProviderService.createToken(null)).thenReturn("<PASSWORD>"); String json = mapper.writeValueAsString(loginRequest); mockMvc.perform(post("/auth/login").contentType(MediaType.APPLICATION_JSON).content(json)) .andExpect(jsonPath("$.accessToken").value("1234567")) .andExpect(status().isOk()); } @Test public void shouldCreateNewUser() throws Exception { SignUpRequest request = new SignUpRequest(); request.setEmail(EMAIL); request.setPassword("<PASSWORD>"); String json = mapper.writeValueAsString(request); mockMvc.perform(post("/auth/sign-up").contentType(MediaType.APPLICATION_JSON).content(json)) .andExpect(jsonPath("$.message").value("User registered successfully !")) .andExpect(status().isOk()); } @Test public void shouldReturnConfirmationMessage() throws Exception { when(verificationTokenService.enableUser("12345")).thenReturn(MESSAGE); mockMvc.perform(get("/auth/verification?token=12345")) .andExpect(jsonPath("$.message").value(MESSAGE)) .andExpect(status().isOk()); } @Test public void shouldResendVerificationEmail() throws Exception { mockMvc.perform(get("/auth/verification/resend?email=" + EMAIL)) .andExpect(jsonPath("$.message").value("The verification email has been resent !")) .andExpect(status().isOk()); } @Test public void shouldSendForgotPasswordUrl() throws Exception { mockMvc.perform(get("/auth/password/forgot?email=" + EMAIL)) .andExpect(jsonPath("$.message").value("An email has been sent !")) .andExpect(status().isOk()); } @Test public void shouldResetPassword() throws Exception { ResetPasswordRequest resetPassword = new ResetPasswordRequest(); resetPassword.setPassword("<PASSWORD>"); resetPassword.setToken("<PASSWORD>"); String json = mapper.writeValueAsString(resetPassword); mockMvc.perform(put("/auth/password/forgot").contentType(MediaType.APPLICATION_JSON).content(json)) .andExpect(jsonPath("$.message").value("The password was changed successfully !")) .andExpect(status().isOk()); } } <file_sep>import {DataPointId} from "./DataPointId"; import {ItemMetric} from "./ItemMetric"; export class DataPoint { id: DataPointId; incomes: Set<ItemMetric>; expenses: Set<ItemMetric>; statistics: Map<String, number>; rates: Map<String, number>; }<file_sep>import {Component, OnInit} from '@angular/core'; import {AuthenticationService} from "../service/authentication.service"; import {Router} from "@angular/router"; import {MatDialog, MatDialogRef} from "@angular/material"; import {ItemDialogComponent} from "../item-dialog/item-dialog.component"; import {AccountService} from "../service/account.service"; import {Account} from "../domain/Account"; import {Item} from "../domain/Item"; import {ToastrService} from "ngx-toastr"; import * as $ from 'jquery'; import {IconService} from "../service/icon.service"; @Component({ selector: 'app-account', templateUrl: './account.component.html', styleUrls: ['./account.component.css'] }) export class AccountComponent implements OnInit { public account: Account; constructor(private authService: AuthenticationService, private router: Router, public dialog: MatDialog, private accountService: AccountService, private toaster: ToastrService, public iconService: IconService) { } ngOnInit() { this.accountService.getCurrentAccount().subscribe(result => { this.account = result; if (this.account.incomes == null) { this.account.incomes = [] } if (this.account.expenses == null) { this.account.expenses = [] } }) } public navigateToStatistics() { this.router.navigate(['/statistics']) } public openUpdateIncome(index: number) { let dialog = this.openItemDialog(this.account.incomes[index]); dialog.componentInstance.title = "Update Income"; dialog.componentInstance.icons = IconService.getIncomeIcons(); dialog.afterClosed().subscribe(result => { if (result != null) { this.account.incomes[index] = result; } }); } public openUpdateExpense(index: number) { let dialog = this.openItemDialog(this.account.expenses[index]); dialog.componentInstance.title = "Update Expense"; dialog.componentInstance.icons = IconService.getExpenseIcons(); dialog.afterClosed().subscribe(result => { if (result != null) { this.account.expenses[index] = result; } }); } public openAddIncome() { let dialog = this.openItemDialog(null); dialog.componentInstance.title = "Add Income"; dialog.componentInstance.icons = IconService.getIncomeIcons(); dialog.afterClosed().subscribe(result => { if (result != null) { this.account.incomes.push(result); } }); } public openAddExpense() { let dialog = this.openItemDialog(null); dialog.componentInstance.title = "Add Expense"; dialog.componentInstance.icons = IconService.getExpenseIcons(); dialog.afterClosed().subscribe(result => { if (result != null) { this.account.expenses.push(result); } }); } public saveAccount() { this.accountService.saveAccount(this.account).subscribe(() => { this.toaster.success('The account was successfully saved !', 'Success'); }, error => { this.toaster.error('An error occur during the saving !', 'Error'); }); } public incomeDown() { AccountComponent.down("income"); } public incomeUp() { AccountComponent.up("income"); } public expenseDown() { AccountComponent.down("expense"); } public expenseUp() { AccountComponent.up("expense"); } private static up(id: String) { var slider = $("#" + id + "slider"); var sliderOffset = $(slider).position().top; var itemHeight = 70; var scroll = Math.abs(sliderOffset) + itemHeight; $('#' + id + 'frame').animate({ scrollTop: scroll }, 'slow'); } private static down(id: String) { var slider = $("#" + id + "slider"); var sliderOffset = $(slider).position().top; var itemHeight = 70; if (sliderOffset < 0) { var lastElementOnScreen = Math.abs(Math.round(sliderOffset / itemHeight)) - 1; $('#' + id + 'frame').animate({ scrollTop: lastElementOnScreen * itemHeight }, 'slow'); } } private openItemDialog(item: Item): MatDialogRef<ItemDialogComponent, any> { return this.dialog.open(ItemDialogComponent, { width: '250px', data: item }); } } <file_sep>import {Injectable} from '@angular/core'; import {Router} from "@angular/router"; import {HttpClient, HttpHeaders} from "@angular/common/http"; import {Observable} from "rxjs/internal/Observable"; import {ResetPassword} from "../domain/ResetPassword"; import {ApiResponse} from "../domain/ApiResponse"; import {AuthRequest} from "../domain/AuthRequest"; import {AuthResponse} from "../domain/AuthResponse"; @Injectable({ providedIn: 'root' }) export class AuthenticationService { private createUserUrl = "api/uaa/auth/sign-up"; private tokenRequest = 'api/uaa/auth/login'; private resendVerificationEmailUrl = "api/uaa/auth/verification/resend"; private verificationEmailUrl = "api/uaa/auth/verification"; private forgotPasswordUrl = "api/uaa/auth/password/forgot"; private changePasswordUrl = "api/uaa/users/change/password"; constructor(private router: Router, private http: HttpClient) { } public createUser(user: AuthRequest): Observable<ApiResponse> { return this.http.post<ApiResponse>(this.createUserUrl, user); } public obtainAccessToken(authRequest: AuthRequest): Observable<AuthResponse> { return this.http.post<AuthResponse>(this.tokenRequest, authRequest); } public resendVerificationEmail(email: String): Observable<ApiResponse> { return this.http.get<ApiResponse>(this.resendVerificationEmailUrl + "?email=" + email); } public forgotPassword(email: String): Observable<ApiResponse> { return this.http.get<ApiResponse>(this.forgotPasswordUrl + "?email=" + email); } public resetPassword(resetPassword: ResetPassword): Observable<ApiResponse> { return this.http.put<ApiResponse>(this.forgotPasswordUrl, resetPassword); } public verifyEmail(toke: String): Observable<ApiResponse> { return this.http.get<ApiResponse>(this.verificationEmailUrl + '?token=' + toke); } public updatePassword(password: String): Observable<ApiResponse> { let token = AuthenticationService.getOauthToken(); let headers = new HttpHeaders({'Authorization': 'Bearer ' + token}); let options = { headers: headers }; return this.http.post<ApiResponse>(this.changePasswordUrl, password, options); } public static getOauthToken(): string { return localStorage.getItem('access_token'); } public static getUsername(): string { return localStorage.getItem("username"); } public static isUserLogin(): boolean { return localStorage.getItem('access_token') != null; } public logout() { localStorage.removeItem('access_token'); localStorage.removeItem('username'); this.router.navigate(['']); } public saveCredentials(token, username, rememberMe: Boolean) { let expireDate; if (rememberMe) { expireDate = new Date(Date.now() + 1000000); } else { expireDate = Date.now(); } localStorage.setItem("access_token", token); localStorage.setItem("username", username); this.router.navigate(['/statistics']); } public static isInRoles(roleList: Array<string>): boolean { //TODO return true; } } <file_sep>import {animate, state, style, transition, trigger} from "@angular/animations"; import {AccountSection} from "../account-section"; import {ChangeDetectorRef, Component} from "@angular/core"; import {ToastrService} from "ngx-toastr"; @Component({ selector: 'app-social-media-connection', templateUrl: './social-media-connection.component.html', styleUrls: ['./social-media-connection.component.css'], animations: [ trigger('showSocial', [ state('true', style({opacity: 1, transform: 'translateY(0%)'})), state('false', style({opacity: 0, transform: 'translateY(25%)'})), transition('false => true', animate('1s 2s ease-in')) ]) ] }) export class SocialMediaConnectionComponent extends AccountSection { constructor(cdr: ChangeDetectorRef, toaster: ToastrService) { super(cdr, toaster); } } <file_sep>package com.money.management.statistics.repository; import com.google.common.collect.ImmutableMap; import com.money.management.statistics.StatisticsApplication; import com.money.management.statistics.domain.timeseries.DataPoint; import com.money.management.statistics.domain.timeseries.ItemMetric; import com.money.management.statistics.domain.timeseries.StatisticMetric; import com.money.management.statistics.util.DataPointUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.math.BigDecimal; import java.util.Date; import java.util.List; import static org.junit.Assert.assertEquals; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = StatisticsApplication.class) public class DataPointRepositoryTest { @Autowired private DataPointRepository repository; @Test public void shouldGetDataPointsBetweenDates() { DataPoint point = createDataPoint(); repository.save(createDataPoint()); List<DataPoint> points; points = repository.findByIdAccountBetweenDates(point.getId().getAccount(), new Date(-1), new Date(1)); assertEquals(1, points.size()); areEquals(point, points.get(0)); points = repository.findByIdAccountBetweenDates(point.getId().getAccount(), new Date(0), new Date(1)); assertEquals(1, points.size()); areEquals(point, points.get(0)); points = repository.findByIdAccountBetweenDates(point.getId().getAccount(), new Date(-1), new Date(0)); assertEquals(1, points.size()); areEquals(point, points.get(0)); points = repository.findByIdAccountBetweenDates(point.getId().getAccount(), new Date(0), new Date(0)); assertEquals(1, points.size()); areEquals(point, points.get(0)); points = repository.findByIdAccountBetweenDates(point.getId().getAccount(), new Date(1), new Date(2)); assertEquals(0, points.size()); points = repository.findByIdAccountBetweenDates(point.getId().getAccount(), new Date(1), new Date(-1)); assertEquals(0, points.size()); } @Test public void shouldSaveDataPoint() { DataPoint point = createDataPoint(); repository.save(point); List<DataPoint> points = repository.findByIdAccount(point.getId().getAccount()); assertEquals(1, points.size()); areEquals(point, points.get(0)); } @Test public void shouldRewriteDataPointWithinADay() { BigDecimal lateAmount = new BigDecimal(200); DataPoint earlier = DataPointUtil.getDataPoint(ImmutableMap.of( StatisticMetric.SAVING_AMOUNT, new BigDecimal(100) ), null); repository.save(earlier); DataPoint later = DataPointUtil.getDataPoint(ImmutableMap.of( StatisticMetric.SAVING_AMOUNT, lateAmount ), null); repository.save(later); List<DataPoint> points = repository.findByIdAccount(later.getId().getAccount()); assertEquals(1, points.size()); assertEquals(lateAmount, points.get(0).getStatistics().get(StatisticMetric.SAVING_AMOUNT)); } private DataPoint createDataPoint() { ItemMetric salary = new ItemMetric("salary", new BigDecimal(20_000)); ItemMetric grocery = new ItemMetric("grocery", new BigDecimal(1_000)); ItemMetric vacation = new ItemMetric("vacation", new BigDecimal(2_000)); return DataPointUtil.getDataPoint(ImmutableMap.of( StatisticMetric.SAVING_AMOUNT, new BigDecimal(400_000), StatisticMetric.INCOMES_AMOUNT, new BigDecimal(20_000), StatisticMetric.EXPENSES_AMOUNT, new BigDecimal(3_000) ), salary, grocery, vacation); } private void areEquals(DataPoint dataPoint1, DataPoint dataPoint2) { assertEquals(dataPoint1.getId().getDate(), dataPoint2.getId().getDate()); assertEquals(dataPoint1.getStatistics().size(), dataPoint2.getStatistics().size()); assertEquals(dataPoint1.getIncomes().size(), dataPoint2.getIncomes().size()); assertEquals(dataPoint1.getExpenses().size(), dataPoint2.getExpenses().size()); } } <file_sep>FROM openjdk:11-jdk ADD ./build/libs/account-service-1.0-SNAPSHOT.jar /app/ ENTRYPOINT ["java", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:6005", "-jar", "/app/account-service-1.0-SNAPSHOT.jar"] EXPOSE 6000 6005<file_sep>import {Injectable} from '@angular/core'; import {HttpClient, HttpHeaders} from "@angular/common/http"; import {Observable} from "rxjs"; import {AuthenticationService} from "./authentication.service"; import {Account} from "../domain/Account"; @Injectable({ providedIn: 'root' }) export class AccountService { private currentAccountUrl = 'api/accounts/current'; constructor(private http: HttpClient) { } public getCurrentAccount(): Observable<Account> { let account = AccountService.getCurrentAccountFromSession(); if (account == null) { return this.requestServer(); } return new Observable(obs => { obs.next(account); }) } public saveAccount(account: Account): Observable<void> { let token = AuthenticationService.getOauthToken(); let headers = new HttpHeaders({'Authorization': 'Bearer ' + token}); let options = { headers: headers }; let request = this.http.put<void>(this.currentAccountUrl, account, options); request.subscribe(() => { AccountService.saveAccount(account); }); return request; } private static getCurrentAccountFromSession(): Account { return JSON.parse(localStorage.getItem('account')) } private requestServer(): Observable<Account> { var observable = this.createRequest(); observable.subscribe(result => AccountService.saveAccount(result)); return observable; } private createRequest(): Observable<Account> { let token = AuthenticationService.getOauthToken(); let headers = new HttpHeaders({'Authorization': 'Bearer ' + token}); let options = { headers: headers }; return this.http.get<Account>(this.currentAccountUrl, options); } private static saveAccount(account: Account) { localStorage.setItem('account', JSON.stringify(account)); } } <file_sep>import {AfterViewInit, ChangeDetectorRef, Component, HostListener, OnInit} from '@angular/core'; import {animate, state, style, transition, trigger} from "@angular/animations"; @Component({ selector: 'app-front-page', templateUrl: './front-page.component.html', styleUrls: ['./front-page.component.css'], animations: [ trigger('showMessage1', [ state('true', style({opacity: 1})), state('false', style({opacity: 0})), transition('true => false', animate(1000)) ]), trigger('showMessage2', [ state('true', style({opacity: 1})), state('false', style({opacity: 0})), transition('false => true', animate('1s 1s ease-in')) ]), trigger('showSection1', [ state('true', style({opacity: 1, transform: 'translateY(0%)'})), state('false', style({opacity: 0, transform: 'translateY(50%)'})), transition('false => true', animate('1s 1.5s ease-in')) ]), trigger('showSection2', [ state('true', style({opacity: 1, transform: 'translateY(0%)'})), state('false', style({opacity: 0, transform: 'translateY(50%)'})), transition('false => true', animate('1s 2s ease-in')) ]), trigger('showSection3', [ state('true', style({opacity: 1, transform: 'translateY(0%)'})), state('false', style({opacity: 0, transform: 'translateY(25%)'})), transition('false => true', animate('1s 0.5s ease-in')) ]), trigger('showSection4', [ state('true', style({opacity: 1, transform: 'translateY(0%)'})), state('false', style({opacity: 0, transform: 'translateY(25%)'})), transition('false => true', animate('1s 1s ease-in')) ]), trigger('showSection5', [ state('true', style({opacity: 1, transform: 'translateY(0%)'})), state('false', style({opacity: 0, transform: 'translateY(25%)'})), transition('false => true', animate('1s 2s ease-in')) ]) ] }) export class FrontPageComponent implements OnInit, AfterViewInit { private windowHeight: number; private scrollPosition: number; public showHeaderSection: boolean = false; public showBeTheFirstSection: boolean = false; public showMainInfoSection: boolean = false; public showPricingSection: boolean = false; constructor(private cdr: ChangeDetectorRef) { } ngOnInit() { this.windowHeight = window.innerHeight; } ngAfterViewInit(): void { this.scrollPosition = window.pageYOffset; this.checkShowSections(); this.cdr.detectChanges(); } @HostListener('window:scroll', ['$event']) checkScroll() { this.scrollPosition = window.pageYOffset; this.checkShowSections(); } @HostListener('window:resize', ['$event']) onResize() { this.scrollPosition = window.pageYOffset; this.windowHeight = window.innerHeight; this.checkShowSections(); } private checkShowSections() { this.showHeaderSection = this.isScrollPositionBetweenWindowSeize(this.showHeaderSection, 0.0, 0.5); this.showBeTheFirstSection = this.isScrollPositionBetweenWindowSeize(this.showBeTheFirstSection, 0.5, 1.5); this.showMainInfoSection = this.isScrollPositionBetweenWindowSeize(this.showMainInfoSection, 1.5, 2.5); this.showPricingSection = this.isScrollPositionBetweenWindowSeize(this.showPricingSection, 3, 4); } private isScrollPositionBetweenWindowSeize(currentState: boolean, ratio1: number, ratio2: number): boolean { return currentState || (this.windowHeight * ratio1 <= this.scrollPosition && this.scrollPosition <= this.windowHeight * ratio2); } } <file_sep>rootProject.name = 'statistics-service'<file_sep>package com.money.management.auth.service; import com.money.management.auth.domain.User; import com.money.management.auth.domain.VerificationToken; public interface VerificationTokenService { VerificationToken create(User user); String enableUser(String token); void resendMailVerification(String email); } <file_sep>package com.money.management.auth.security.oauth2; import com.money.management.auth.domain.AuthProvider; import com.money.management.auth.domain.User; import com.money.management.auth.exception.OAuth2AuthenticationProcessingException; import com.money.management.auth.repository.UserRepository; import com.money.management.auth.security.oauth2.user.OAuth2UserInfo; import com.money.management.auth.security.oauth2.user.OAuth2UserInfoFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.InternalAuthenticationServiceException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.util.Collections; import java.util.Optional; @Service public class OAuth2UserService extends DefaultOAuth2UserService { private UserRepository userRepository; @Autowired public OAuth2UserService(UserRepository userRepository) { this.userRepository = userRepository; } @Override public OAuth2User loadUser(OAuth2UserRequest oAuth2UserRequest) throws OAuth2AuthenticationException { OAuth2User oAuth2User = super.loadUser(oAuth2UserRequest); try { return processOAuth2User(oAuth2UserRequest, oAuth2User); } catch (AuthenticationException ex) { throw ex; } catch (Exception ex) { throw new InternalAuthenticationServiceException(ex.getMessage(), ex.getCause()); } } private OAuth2User processOAuth2User(OAuth2UserRequest oAuth2UserRequest, OAuth2User oAuth2User) { OAuth2UserInfo oAuth2UserInfo = OAuth2UserInfoFactory.getOAuth2UserInfo(oAuth2UserRequest.getClientRegistration().getRegistrationId(), oAuth2User.getAttributes()); String email = getEmail(oAuth2UserInfo); Optional<User> userOptional = userRepository.findUsersByUsername(email); User user; if (userOptional.isPresent()) { user = userOptional.get(); verifyUserProvider(user, oAuth2UserRequest); } else { user = registerNewUser(oAuth2UserRequest, oAuth2UserInfo); } user.setAttributes(oAuth2User.getAttributes()); return user; } private User registerNewUser(OAuth2UserRequest oAuth2UserRequest, OAuth2UserInfo oAuth2UserInfo) { User user = new User(); user.setProvider(AuthProvider.getProvider(oAuth2UserRequest.getClientRegistration().getRegistrationId())); user.setProviderId(oAuth2UserInfo.getId()); user.setUsername(oAuth2UserInfo.getEmail()); user.setEnabled(true); user.setAuthorities(Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))); return userRepository.save(user); } private String getEmail(OAuth2UserInfo oAuth2UserInfo) { if (oAuth2UserInfo == null || StringUtils.isEmpty(oAuth2UserInfo.getEmail())) { throw new OAuth2AuthenticationProcessingException("Email not found from OAuth2 provider"); } return oAuth2UserInfo.getEmail(); } private void verifyUserProvider(User user, OAuth2UserRequest oAuth2UserRequest) { if (!user.getProvider().equals(AuthProvider.getProvider(oAuth2UserRequest.getClientRegistration().getRegistrationId()))) { throw new OAuth2AuthenticationProcessingException("Looks like you're signed up with " + user.getProvider() + " account. Please use your " + user.getProvider() + " account to login."); } } } <file_sep>import {Component} from '@angular/core'; import {animate, state, style, transition, trigger} from "@angular/animations"; import {AccountSection} from "./account-section"; @Component({ selector: 'app-account-section', templateUrl: './account-section.component.html', styleUrls: ['./account-section.component.css'], animations : [ trigger('showBar', [ state('true', style({opacity: 1, transform: 'translateY(0%)'})), state('false', style({opacity: 0, transform: 'translateY(25%)'})), transition('false => true', animate('1s 1s ease-in')) ]) ] }) export class AccountSectionComponent extends AccountSection { } <file_sep>dependencies { compile('org.springframework.boot:spring-boot-starter-web') compile('org.springframework.boot:spring-boot-starter-mail') compile('org.springframework.boot:spring-boot-starter-actuator') compile('org.springframework.boot:spring-boot-starter-security') compile('org.springframework.boot:spring-boot-starter-data-mongodb') compile('org.springframework.cloud:spring-cloud-starter-config') compile('org.springframework.cloud:spring-cloud-starter-oauth2') compile('org.springframework.cloud:spring-cloud-starter-bus-amqp') compile('org.springframework.cloud:spring-cloud-starter-openfeign') compile('org.springframework.cloud:spring-cloud-netflix-hystrix-stream') compile('org.springframework.cloud:spring-cloud-starter-netflix-eureka-client') compile('com.googlecode.json-simple:json-simple:1.1.1') compile('com.google.guava:guava:27.0.1-jre') compile('org.springframework.security.oauth:spring-security-oauth2') testCompile('com.jayway.jsonpath:json-path:2.2.0') testCompile('de.flapdoodle.embed:de.flapdoodle.embed.mongo') }<file_sep>FROM openjdk:11-jdk ADD ./build/libs/notification-service-1.0-SNAPSHOT.jar /app/ ENTRYPOINT ["java", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8005", "-jar", "/app/notification-service-1.0-SNAPSHOT.jar"] EXPOSE 8000 8005<file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { SocialMediaConnectionComponent } from './social-media-connection.component'; describe('SocialMediaConnectionComponent', () => { let component: SocialMediaConnectionComponent; let fixture: ComponentFixture<SocialMediaConnectionComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ SocialMediaConnectionComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(SocialMediaConnectionComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>package com.money.management.auth.repository; import com.money.management.auth.AuthApplication; import com.money.management.auth.domain.User; import com.money.management.auth.domain.VerificationToken; import com.money.management.auth.util.UserUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.time.LocalDateTime; import java.util.function.Function; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = AuthApplication.class) public class VerificationTokenRepositoryTest { @Autowired private VerificationTokenRepository repository; @Test public void shouldSaveAndFindByToken() { compareVerificationTokens(verificationToken -> repository.findByToken(verificationToken.getToken())); } @Test public void shouldSaveAndFindByUsername() { compareVerificationTokens(verificationToken -> repository.findByUserUsername(verificationToken.getUser().getUsername())); } private void compareVerificationTokens(Function<VerificationToken, VerificationToken> function) { VerificationToken saved = createAndSaveVerificationToken(); User savedUser = saved.getUser(); VerificationToken found = function.apply(saved); User foundUser = found.getUser(); assertVerificationToken(found, saved); assertUser(savedUser, foundUser); } private void assertVerificationToken(VerificationToken actual, VerificationToken expected) { assertThat(actual.getExpireDate().getDayOfYear(), is(expected.getExpireDate().getDayOfYear())); assertThat(actual.getToken(), is(expected.getToken())); } private void assertUser(User expected, User actual) { assertThat(expected.getUsername(), is(actual.getUsername())); assertThat(expected.getPassword(), is(actual.getPassword())); } private VerificationToken createAndSaveVerificationToken() { User savedUser = UserUtil.getUser(); VerificationToken saved = new VerificationToken(); saved.setToken("<PASSWORD>"); saved.setUser(savedUser); saved.setExpireDate(LocalDateTime.now()); repository.save(saved); return saved; } } <file_sep>package com.money.management.statistics.util; import com.google.common.collect.Sets; import com.money.management.statistics.domain.timeseries.DataPoint; import com.money.management.statistics.domain.timeseries.DataPointId; import com.money.management.statistics.domain.timeseries.ItemMetric; import com.money.management.statistics.domain.timeseries.StatisticMetric; import java.math.BigDecimal; import java.util.Date; import java.util.Map; public class DataPointUtil { private DataPointUtil() { } public static DataPoint getDataPoint(Map<StatisticMetric, BigDecimal> statistics, ItemMetric income, ItemMetric... expenses) { DataPointId pointId = new DataPointId("test-account", new Date(0)); DataPoint point = new DataPoint(); point.setId(pointId); point.setIncomes(Sets.newHashSet(income)); point.setExpenses(Sets.newHashSet(expenses)); point.setStatistics(statistics); return point; } } <file_sep>#!/usr/bin/env bash export STATISTICS_SERVICE_PASSWORD="<PASSWORD>" export NOTIFICATION_SERVICE_PASSWORD="<PASSWORD>" export ACCOUNT_SERVICE_PASSWORD="<PASSWORD>" export MONGODB_PASSWORD="<PASSWORD>" docker-compose -f docker-compose.yml -f docker-compose.dev.yml up
f74f325ecbb8cb558b88332d118693a3e0f82144
[ "JavaScript", "Gradle", "Java", "TypeScript", "Dockerfile", "Shell" ]
70
TypeScript
Daniel194/Money-Management
a7ea14df66bc729f85f0940d52800ce5a5445fac
bce1edffc6f3742c102b1b6273c3ec7e05d740cc
refs/heads/master
<repo_name>HectorRubi/API-Laravel<file_sep>/tests/Feature/Http/Controllers/Api/PostControllerTest.php <?php namespace Tests\Feature\Http\Controllers\Api; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\WithFaker; use Tests\TestCase; use App\Post; use App\User; class PostControllerTest extends TestCase { use RefreshDatabase; public function testStore() { // $this->withoutExceptionHandling(); $user = factory(User::class)->create(); $response = $this->actingAs($user, 'api')->json('POST', '/api/posts', [ 'title' => 'El post de prueba' ]); $response->assertJsonStructure(['id', 'title', 'created_at', 'updated_at']) ->assertJson(['title' => 'El post de prueba']) ->assertStatus(201); // OK, creado un recurso $this->assertDatabaseHas('posts', ['title' => 'El post de prueba']); } public function testValidateTitle() { $user = factory(User::class)->create(); $response = $this->actingAs($user, 'api')->json('POST', '/api/posts', [ 'title' => '' ]); $response->assertStatus(422); // Estatus HTTP 422 - Fue imposible completarla $response->assertJsonValidationErrors('title'); } public function testShow() { $post = factory(Post::class)->create(); $user = factory(User::class)->create(); $response = $this->actingAs($user, 'api')->json('GET', "/api/posts/$post->id"); // id = 1 $response->assertJsonStructure(['id', 'title', 'created_at', 'updated_at']) ->assertJson(['title' => $post->title]) ->assertStatus(200); // OK } public function test404Show() { $user = factory(User::class)->create(); $response = $this->actingAs($user, 'api')->json('GET', '/api/posts/1000'); $response->assertStatus(404); // Not found } public function testUpdate() { // $this->withoutExceptionHandling(); $post = factory(Post::class)->create(); $user = factory(User::class)->create(); $response = $this->actingAs($user, 'api')->json('PUT', "/api/posts/$post->id", [ 'title' => 'nuevo' ]); $response->assertJsonStructure(['id', 'title', 'created_at', 'updated_at']) ->assertJson(['title' => 'nuevo']) ->assertStatus(200); // OK $this->assertDatabaseHas('posts', ['title' => 'nuevo']); } public function testDelete() { // $this->withoutExceptionHandling(); $post = factory(Post::class)->create(); $user = factory(User::class)->create(); $response = $this->actingAs($user, 'api')->json('DELETE', "/api/posts/$post->id"); $response->assertSee(null) ->assertStatus(204); // OK, sin contenido $this->assertDatabaseMissing('posts', ['id' => $post->id]); } public function testIndex() { factory(Post::class, 5)->create(); $user = factory(User::class)->create(); $response = $this->actingAs($user, 'api')->json('GET', '/api/posts'); $response->assertJsonStructure([ 'data' => [ '*' => ['id', 'title', 'created_at', 'updated_at'] ] ])->assertStatus(200); // OK } public function testGuest() { $this->json('GET', '/api/posts')->assertStatus(401); $this->json('POST', '/api/posts')->assertStatus(401); $this->json('GET', '/api/posts/1000')->assertStatus(401); $this->json('PUT', '/api/posts/1000')->assertStatus(401); $this->json('DELETE', '/api/posts/1000')->assertStatus(401); } }
8207fd1a028a7fe73df1635599a59eccf7b3fb5f
[ "PHP" ]
1
PHP
HectorRubi/API-Laravel
99223cc8386a324694424852b87b5d0a91120f0b
8b2a363d5774b542410f0124918eb9d4d6df9301
refs/heads/master
<repo_name>emarchiol/factoryReflection<file_sep>/ConsoleApplication1/CollectionGenerator.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; using System.Collections; using System.Xml; using System.IO; using System.Xml.Serialization; namespace ConsoleApplication1 { class CollectionGenerator { string xmlCore; string ggeName; int ggeQuantity; public static List<IGenericGameElement> gges = new List<IGenericGameElement>(); public void go() { GGEFactory factory = new GGEFactory(); //Factory IGenericGameElement objetoGGE = factory.CreateInstance("GGECard"); if (objetoGGE == null) return; ReadCoreXML("C:\\loveLetter\\"); Console.ReadLine(); } //METODOS public IGenericGameElement ReadSerialized(IGenericGameElement gge, string path, string type) { GGEFactory fac = new GGEFactory(); //GGECard card = new GGECard(); IGenericGameElement ggeUnknow; path = "C:\\loveLetter"; string ggePath = path + "\\app\\" + this.ggeName + ".xml"; //Reflection get type Type MyType = Type.GetType("ConsoleApplication1."+type); XmlSerializer serializer = new XmlSerializer(MyType); FileStream stream = new FileStream(ggePath, FileMode.Open); Console.WriteLine("Hurray gge XML cargado"); try { ggeUnknow = serializer.Deserialize(stream) as IGenericGameElement; } catch (Exception e) { Console.WriteLine("Invalid XML"); Console.WriteLine(e); ggeUnknow = fac.CreateInstance("GGECard"); } finally { stream.Close(); } return ggeUnknow; } //Abrir el XML y leerlo public void ReadCoreXML(string path) { IGenericGameElement gge; string xmlValue; GGEFactory factory = new GGEFactory(); //Ubico el archivo xml principal try { Console.WriteLine(path); if (File.Exists(path + "core.xml")) { Console.WriteLine("Hurray archivo core.xml encontrado"); StreamReader sr = new StreamReader(path + "core.xml"); xmlCore = sr.ReadToEnd(); } else { Console.WriteLine("core no existe"); } } catch (Exception e) { Console.WriteLine("File not found or corrupt."); Console.WriteLine(e.Message); } Console.ReadLine(); //Reading game objects XmlReader reader = XmlReader.Create(new StringReader(xmlCore)); //Game options //Collection elements int breaker = 0; try { reader.ReadToFollowing("Collection"); do { reader.MoveToFirstAttribute(); xmlValue = reader.Value.ToString(); Console.WriteLine("Atributo:" + reader.Value); string ggeType = reader.Value; //El xml me indicara cuantas copias de cada objeto hay (por ejemplo cartas iguales), con ese quantity genero x cantidad de GGE if (xmlValue.CompareTo("GGEToken") ==0 || xmlValue.CompareTo("GGECard") == 0) { reader.MoveToNextAttribute(); ggeQuantity = Convert.ToInt16(reader.Value); reader.MoveToNextAttribute(); ggeName = reader.Value; for (int i = 0; i < ggeQuantity; i++) { gge = factory.CreateInstance(ggeType); gge = ReadSerialized(gge, path, ggeType); gges.Add(gge); Console.WriteLine("recolectando objetos..."); Console.WriteLine("====="); gge.printAtt(); Console.WriteLine("====="); } } breaker++; } while (reader.ReadToFollowing("Collection") && !reader.EOF); } catch (Exception e) { Console.WriteLine("Something went wrong:" + e); } } } }<file_sep>/ConsoleApplication1/IGenericGameElement.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { public interface IGenericGameElement { int Type { get; set; } string RatioW { get; set; } string RatioH { get; set; } string Name { get; set; } string ExternalValue { get; set; } string InternalValue { get; set; } void flip(); void printAtt(); } } <file_sep>/ConsoleApplication1/GGECard.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Reflection; namespace ConsoleApplication1 { public class GGECard : IGenericGameElement { public int Type{ get; set; } public string RatioW { get; set; } public string RatioH { get; set; } public string Name { get; set; } public string FrontImage; public string BackImage; public string ExternalValue { get; set; } public string InternalValue { get; set; } public void flip() { Console.WriteLine("La carta se dió vuelta"); } public void printAtt() { Console.WriteLine("Name: " + Name); Console.WriteLine("Type: " + Type); Console.WriteLine("RatioW: " + RatioW); Console.WriteLine("RatioH: " + RatioH); Console.WriteLine("FrontImage: " + FrontImage); Console.WriteLine("BackImage: " + BackImage); Console.WriteLine("ExternalValue: " + ExternalValue); Console.WriteLine("InternalValue: " + InternalValue); } } } <file_sep>/ConsoleApplication1/GGEFactory.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { public class GGEFactory { public IGenericGameElement CreateInstance(string tipoGGE) { IGenericGameElement objetoGGE; switch (tipoGGE) { case "GGECard": objetoGGE = new GGECard(); break; case "GGEToken": objetoGGE = new GGEToken(); break; default: objetoGGE = null; break; } return objetoGGE; } } } <file_sep>/ConsoleApplication1/GGEToken.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { public class GGEToken : IGenericGameElement { public int Type { get; set; } public string RatioW { get; set; } public string RatioH { get; set; } public string Name { get; set; } public string TokenValue; public string ExternalValue { get; set; } public string InternalValue { get; set; } public void flip() { Console.WriteLine("La carta se dió vuelta"); } public void printAtt() { Console.WriteLine("Name: "+Name); Console.WriteLine("Type: " + Type); Console.WriteLine("RatioW: " + RatioW); Console.WriteLine("RatioH: " + RatioH); Console.WriteLine("TokenValue: " + TokenValue); Console.WriteLine("ExternalValue: " + ExternalValue); Console.WriteLine("InternalValue: " + InternalValue); } } }
50e2c7b8e98317089d8ae0ff4c7f3a66d08076b6
[ "C#" ]
5
C#
emarchiol/factoryReflection
99c226b1ce96e6577059d5091e0fdc8c1b491b7b
026ca681d40e3e22a524da03ea8e05d9a8c8d78d
refs/heads/master
<file_sep>require 'ffi' require 'cupsffi/lib' require 'cupsffi/printer' require 'cupsffi/job' require 'cupsffi/ppd' <file_sep>CupsFFI is an FFI wrapper around libcups providing access to the Cups API as well as the PPD API. It was written using Ruby 1.9.2 but has not been tested with previous versions. == Author <NAME> www.tebros.com == License CupsFFI is MIT licensed. == Installation gem install cupsffi == Setup Nothing required. libcups is used to find and read all configuration. == Example usage require 'cupsffi' # Returns array of printer names: # => ["HP-Officejet-7200-series", "test-printer"] printers = CupsPrinter.get_all_printer_names printer = CupsPrinter.new(printers.first) # Returns a hash of the Cups printer options: # => {"auth-info-required"=>"none", # "copies"=>"1", # "device-uri"=>"ipp://192.168.250.55/ipp/3000", ... printer.attributes # Return a hash of :state and :reasons. # :state is :idle, :printing, or :stopped. For example: # {:state=>:idle, :reasons=>["none"]} printer.state # Print a file (pdf, jpg, ps, etc.). You can pass in a hash of printer # options if you want to override the printer's defaults. A CupsJob object # is returned. CupsJob can be used to check on the job status. job = printer.print_file('/tmp/example.jpg', {'InputSlot' => 'Upper', 'PageSize' => 'A4'}) # A job's status is a CupsFFI::IppJState enumeration: # [:pending, :held, :processing, :stopped, :canceled, :aborted, :completed] job.status # Cancel a specific job job.cancel # Print a binary blob of data. The data should be in a String, and is # passed to libcups as a char array. You must also specify the mime type. # Like print_file, printer options are... optional. A CupsJob object is # returned. job = printer.print_data('hello world', 'text/plain') # Cancel all outstanding jobs on the printer printer.cancel_all_jobs == Remote CUPS Server You may pass in :hostname and :port arguments when creating a CupsPrinter instance or querying for available printers. remote_printers = CupsPrinter.get_all_printer_names(:hostname => 'print.example.com') print = CupsPrinter.new(remote_printers.first, :hostname => 'print.example.com') <file_sep># The MIT License # # Copyright (c) 2011 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. class CupsPPD def initialize(printer_name, connection) @file = CupsFFI::cupsGetPPD2(connection, printer_name) raise "No PPD found for #{printer_name}" if @file.nil? @pointer = CupsFFI::ppdOpenFile(@file) raise "Unable to open PPD #{file}" if @pointer.null? @ppd_file_s = CupsFFI::PPDFileS.new(@pointer) end def close CupsFFI::ppdClose(@pointer) File.unlink(@file) end def options options = [] option_pointer = CupsFFI::ppdFirstOption(@pointer) while !option_pointer.null? option = CupsFFI::PPDOptionS.new(option_pointer) choices = [] option[:num_choices].times do |i| choice = CupsFFI::PPDChoiceS.new(option[:choices] + (CupsFFI::PPDChoiceS.size * i)) choices.push({ :text => String.new(choice[:text]), :choice => String.new(choice[:choice]) }) end options.push({ :keyword => String.new(option[:keyword]), :default_choice => String.new(option[:defchoice]), :text => String.new(option[:text]), :ui => String.new(option[:ui].to_s), :section => String.new(option[:section].to_s), :order => option[:order], :choices => choices }) option_pointer = CupsFFI::ppdNextOption(@pointer) end options end def attributes attributes = [] attr_ptr = @ppd_file_s[:attrs].read_pointer if !attr_ptr.null? @ppd_file_s[:attrs].get_array_of_pointer(0, @ppd_file_s[:num_attrs]).each do |attr_ptr| attribute = CupsFFI::PPDAttrS.new(attr_ptr) attributes.push({ :name => String.new(attribute[:name]), :spec => String.new(attribute[:spec]), :text => String.new(attribute[:text]), :value => String.new(attribute[:value]), }) end end attributes end def attribute(name, spec=nil) attributes = [] attribute_pointer = CupsFFI::ppdFindAttr(@pointer, name, spec) while !attribute_pointer.null? attribute = CupsFFI::PPDAttrS.new(attribute_pointer) attributes.push({ :name => String.new(attribute[:name]), :spec => String.new(attribute[:spec]), :text => String.new(attribute[:text]), :value => String.new(attribute[:value]), }) attribute_pointer = CupsFFI::ppdFindNextAttr(@pointer, name, spec) end attributes end def page_size(name=nil) size_ptr = CupsFFI::ppdPageSize(@pointer, name) size = CupsFFI::PPDSizeS.new(size_ptr) if size.null? nil else { :marked => (size[:marked] != 0), :name => String.new(size[:name]), :width => size[:width], :length => size[:length], :margin => { :left => size[:left], :bottom => size[:bottom], :right => size[:right], :top => size[:top] } } end end end
b71f7a5266cce8f3be4435b4691a9a0f3ad54fe1
[ "RDoc", "Ruby" ]
3
Ruby
mykhi/cupsffi
bf7e350b14ae72799f73ba809bcef7aaf7e10f22
5b343c2c459dbf669eb93220ce8f0161e8ee3a22
refs/heads/main
<repo_name>AshraAust136/evaly-selenium-test<file_sep>/src/main/java/org/example/SeleniumTest.java package org.example; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; public class SeleniumTest { @FindBy(css = ".PlnBa button") WebElement closeAd; @FindBy(css = ".cLuHeZ .items-center button:nth-child(4)") WebElement loginPanel; @FindBy(css = "input[name = 'phone']") WebElement textBoxUserName; @FindBy(css = "input[name = 'password']") WebElement textBoxPassword; @FindBy(css = ".kuyfle button") WebElement buttonLogin; @FindBy(css = "a[id = 'all-shops']") WebElement buttonAllShops; @FindBy(css = ".grid a:nth-child(2)") WebElement shopSafwaan; @FindBy(css = ".product-grid .flex-col:nth-child(1) button") WebElement buttonProductPantBuy; @FindBy(css = ".PlnCH .dNDJhI p") WebElement assertionText; public void test() throws InterruptedException { System.setProperty("webdriver.gecko.driver","C:\\Users\\Ashra\\IdeaProjects\\Evaly_QA_Task_1\\driver\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); PageFactory.initElements(driver, this); driver.manage().deleteAllCookies(); Thread.sleep(5000); Helper helper = new Helper(driver); driver.get("https://evaly.com.bd/"); helper.waitFor(closeAd); closeAd.click(); helper.waitFor(loginPanel); loginPanel.click(); helper.waitFor(textBoxUserName); textBoxUserName.sendKeys("01521515792"); textBoxPassword.sendKeys("<PASSWORD>"); buttonLogin.click(); helper.waitFor(buttonAllShops); buttonAllShops.click(); helper.waitFor(shopSafwaan); shopSafwaan.click(); helper.waitFor(buttonProductPantBuy); buttonProductPantBuy.click(); helper.waitFor(assertionText); String assertText = assertionText.getText(); System.out.println(assertText); assert assertText.equals("Select Variant"); driver.quit(); } } <file_sep>/README.md # evaly-selenium-test 1. Change the driver path from src > SeleniumTest.java file. 2. To enable assertion in IntelliJ Idea, please go to Run in the top bar > Edit configurations > Modify options under Build and Run > Add VM options > type "-ea"
394a00a676fe8934ef5f45fa837871d8f98edfa0
[ "Markdown", "Java" ]
2
Java
AshraAust136/evaly-selenium-test
ed088b2b7bed7e4a6a6cfe271e956101d503cf17
2b988a64bfd8109e1e597be45b37d01e4822b525
refs/heads/development
<repo_name>milespratt/avatar-maker-plus<file_sep>/README.md [![Maintainability](https://api.codeclimate.com/v1/badges/2ad655942c945f41a56e/maintainability)](https://codeclimate.com/github/milespratt/avatar-maker-plus/maintainability) [![Test Coverage](https://api.codeclimate.com/v1/badges/2ad655942c945f41a56e/test_coverage)](https://codeclimate.com/github/milespratt/avatar-maker-plus/test_coverage) <img align="right" width="100" height="100" src="https://raw.githubusercontent.com/milespratt/avatar-maker-plus/development/src/assets/user.png"> # Avatar Maker Plus An easy to use avatar creation component with facial detection for React apps. View the [demo](https://avatar-maker-plus.netlify.com). <!-- <p align="center"> --> <img align="center" height="400" src="https://raw.githubusercontent.com/milespratt/avatar-maker-plus/development/src/assets/screenshot.png"> <!-- </p> --> <file_sep>/src/components/AvatarMaker.jsx import React, { useCallback, useState, useRef, useEffect } from "react"; import AvatarEditor from "react-avatar-editor"; import { useDropzone } from "react-dropzone"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faImages, faTimes } from "@fortawesome/free-solid-svg-icons"; import AvatarMakerStyles from "./AvatarMaker.styles"; // facial recognition import * as faceapi from "face-api.js"; const MODEL_URL = "/models"; async function loadModels() { await faceapi.loadSsdMobilenetv1Model(MODEL_URL); await faceapi.loadFaceLandmarkModel(MODEL_URL); await faceapi.loadFaceRecognitionModel(MODEL_URL); await faceapi.loadFaceExpressionModel(MODEL_URL); } loadModels(); export default function AvatarMaker({ className }) { // the image file created via drop zone, or upload const [image, setImage] = useState(null); const [result, setResult] = useState(null); const [processing, setProcessing] = useState(false); // facial recognition details const [faceDetails, setFaceDetails] = useState(null); // dropzone support const onDrop = useCallback(acceptedFiles => { setImage(acceptedFiles[0]); }, []); const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop }); // ref for the editor const editorRef = useRef(null); // sets result image on load and on change of editor function setResultImage() { setResult( editorRef.current.getImageScaledToCanvas().toDataURL("image/png") ); } // draw face details useEffect(() => { if (faceDetails) { const canvas = editorRef.current.canvas.current; faceapi.draw.drawDetections(canvas, faceDetails); faceapi.draw.drawFaceLandmarks(canvas, faceDetails, { drawLines: true }); faceapi.draw.drawFaceExpressions(canvas, faceDetails); } }, [faceDetails]); function processImage() { if (result) { setProcessing(true); async function getFaceData() { let fullFaceDescriptions = await faceapi .detectAllFaces(editorRef.current.getImageScaledToCanvas()) .withFaceLandmarks() .withFaceDescriptors() .withFaceExpressions(); setProcessing(false); setFaceDetails(fullFaceDescriptions); } setTimeout(() => { getFaceData(); }, 500); } } return ( <AvatarMakerStyles className={className}> <button className="avatar__maker__close"> <FontAwesomeIcon className="avatar__maker__close__icon" icon={faTimes} /> </button> <span className="avatar__maker__title">Select profile photo</span> <div className="avatar__dropzone" {...getRootProps()}> {image ? ( <AvatarEditor ref={editorRef} className="avatar__editor" image={image} width={235} height={235} border={0} color={[255, 255, 255, 0.6]} // RGBA scale={1} rotate={0} onImageReady={setResultImage} onPositionChange={setResultImage} /> ) : ( <> <input {...getInputProps()} /> {isDragActive ? ( <p>Drop your photo to begin editing...</p> ) : ( <div className="avatar__dropzone__controls"> <FontAwesomeIcon className="avatar__dropzone__icon" icon={faImages} /> <p className="avatar__dropzone__message avatar__dropzone__message--bold"> Drag a profile photo here </p> <p className="avatar__dropzone__message">- or -</p> <button className="avatar__maker__control avatar__maker__control--slim"> Select from your computer </button> </div> )} </> )} </div> <div className="avatar__maker__controls"> <button onClick={processImage} className={ image && !processing ? "avatar__maker__control" : "avatar__maker__control avatar__maker__control--inactive" } > Set as profile photo </button> <button onClick={() => { setResult(null); setImage(null); }} className={ image && !processing ? "avatar__maker__control avatar__maker__control--secondary" : "avatar__maker__control avatar__maker__control--secondary avatar__maker__control--inactive" } > Cancel </button> {processing && ( <div className="loading__indicator"> <span className="loading__message">Processing image...</span> <div className="loader"></div> </div> )} </div> </AvatarMakerStyles> ); } AvatarMaker.defaultProps = { className: "avatar__maker" }; <file_sep>/src/components/AvatarMaker.styles.js import styled from "styled-components"; const AvatarMakerStyles = styled.div` box-sizing: border-box; height: 373px; width: 675px; background-color: white; border-radius: 5px; display: grid; grid-template-rows: min-content 1fr min-content; grid-template-areas: "title" "editor" "controls"; padding: 20px; grid-row-gap: 20px; position: relative; .avatar__maker__close { position: absolute; color: #67756e; top: 20px; right: 20px; font-size: 21px; padding: 0; background: none; outline: none; border: none; color: #67756e; } .avatar__maker * { box-sizing: border-box; } .avatar__maker__title { grid-area: title; font-weight: bold; font-size: 17px; } .avatar__dropzone { border-radius: 10px; border: 3px dashed #dbd6d1; height: 100%; width: 100%; display: flex; align-items: center; justify-content: center; grid-area: editor; } .avatar__dropzone__message { font-size: 12px; margin: 0; } .avatar__dropzone__message--bold { font-weight: bold; } .avatar__dropzone__controls { display: grid; grid-auto-flow: row; justify-items: center; grid-gap: 10px; } .avatar__dropzone__icon { font-size: 50px; color: #2e4238; } .avatar__maker__controls { grid-area: controls; display: grid; grid-auto-flow: column; grid-template-columns: min-content min-content 1fr; grid-gap: 10px; align-items: center; } .avatar__maker__control { cursor: pointer; font-size: 12px; color: white; background: #67756e; border-radius: 4px; border: none; outline: none; font-weight: bold; padding: 8px 12px; white-space: nowrap; border: 1px solid #67756e; } .avatar__maker__control--secondary { border: 1px solid #67756e; color: #67756e; background: white; } .avatar__maker__control--slim { padding: 4px 12px; font-size: 11px; } .avatar__maker__control--inactive { opacity: 0.5; cursor: default; pointer-events: none; } .loading__indicator { display: flex; align-items: center; justify-self: end; } .loading__message { white-space: nowrap; font-size: 10px; } .loader, .loader:after { border-radius: 50%; width: 20px; height: 20px; } .loader { margin-left: 10px; font-size: 10px; position: relative; text-indent: -9999em; border-top: 2px solid rgba(255, 255, 255, 0.2); border-right: 2px solid rgba(255, 255, 255, 0.2); border-bottom: 2px solid rgba(255, 255, 255, 0.2); border-left: 2px solid black; -webkit-transform: translateZ(0); -ms-transform: translateZ(0); transform: translateZ(0); -webkit-animation: loadSpin 1.1s infinite linear; animation: loadSpin 1.1s infinite linear; } @-webkit-keyframes loadSpin { 0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); } } @keyframes loadSpin { 0% { -webkit-transform: rotate(0deg); transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); } } `; export default AvatarMakerStyles;
59806f1de00de535541ef027b5f82c82f190f70b
[ "Markdown", "JavaScript" ]
3
Markdown
milespratt/avatar-maker-plus
90c96bfe3f6dd51853bc43336cc4ba1ceefcf1a8
15206f13d9fdd9736d9ad8f56565e7cf1d6e2f92
refs/heads/master
<file_sep>import os, io from google.cloud import vision from google.cloud.vision import types import pandas as pd import json from collections import OrderedDict os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'credentials.json' client = vision.ImageAnnotatorClient() # print(dir(client)) client = vision.ImageAnnotatorClient() def detectText(img): with io.open(img, 'rb') as image_file: content = image_file.read() image = vision.types.Image(content=content) response = client.text_detection(image=image) texts = response.text_annotations # print(response) df = pd.DataFrame(columns=['locale','description']) for text in texts: df = df.append( dict( locale = text.locale, description=text.description ), ignore_index=True ) print(df['description'][0]) return df['description'][0] FOLDER_PATH =r'C:/Users/khak1/OneDrive/바탕 화면/임시 컨트리/woojin_940205' file_list=os.listdir(FOLDER_PATH) ID = dict() #for i in range(len(file_list)): 실제 데이터 생성용 #for i in range(0,5): test용 try : content=detectText(os.path.join(FOLDER_PATH,file_list[i])) ID[i]=file_list[i], content except IndexError: continue with open("woojin_940205.json",'w',encoding="utf-8") as make_file: json.dump(ID, make_file, ensure_ascii=False, indent="\t") <file_sep>import csv, json Input = open("kim_hanwoong.json",'rt', encoding='utf-8') data=json.load(Input) Output=open("kim_hanwoong.csv", 'w',newline='', encoding='utf-8-sig') csvwriter=csv.writer(Output) content=list(data.values()) header=["게시글 id", "이미지 본문"] csvwriter.writerow(header) for i in range(len(content)): for j in range(len(content[i])): content[i][j]=content[i][j].replace("\n"," ") for i in range(len(content)): csvwriter.writerow(content[i]) Output.close()
c3cf95fe99bb62e2bd72060fc1eb5af3c138b546
[ "Python" ]
2
Python
Kim-hee-ah/HashTag
7906d08fe3ff24fe656a6a2ca4db3981fde87fae
6772729f67360dd7f797329c0747d6480b767bb2
refs/heads/master
<repo_name>luanngominh/dot-files<file_sep>/update.sh #!/usr/bin/env sh help="Type \"$0 commit\" or \"$0 local\"" [[ $# != 1 ]] && echo $help && exit 0 set -e case $1 in commit) echo "cp ~/.spacemacs .spacemacs" cp ~/.spacemacs .spacemacs echo "cp ~/.zshrc .zshrc" cp ~/.zshrc .zshrc cp ~/.config/starship.toml starship.toml cp ~/.oh-my-zsh/custom/key-binding.zsh .key-binding.zsh cp ~/.alacritty.yml .alacritty.yml ;; local) echo "cp .spacemacs ~/.spacemacs" cp .spacemacs ~/.spacemacs echo "cp .zshrc ~/.zshrc" cp .zshrc ~/.zshrc echo "cp starship.toml ~/.config/starship.toml" cp starship.toml ~/.config/starship.toml echo "cp .key-binding.zsh ~/.oh-my-zsh/custom/key-binding.zsh" cp .key-binding.zsh ~/.oh-my-zsh/custom/key-binding.zsh cp .alacritty.yml ~/.alacritty.yml ;; *) echo $help ;; esac <file_sep>/.key-binding.zsh [[ `uname -s` = "Darwin" ]] && bindkey '^F' autosuggest-accept [[ `uname -s` = "Linux" ]] && bindkey '^ ' autosuggest-accept <file_sep>/starship.toml [kubernetes] disabled = false symbol = "⛵ " [memory_usage] disabled = true threshold = -1 symbol = " " style = "bold dimmed green" <file_sep>/README.md # Update dot file script * Add dot file from local to git: ./update.sh commit * Add dot file from git to local: ./update.sh local # ZSH ## Install Oh My Zsh * Install zsh * Install oh my zsh ```shell sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" ``` # Spacemacs ## Install zsh-autosuggestions (shell Oh My ZSH) ```shell git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions ``` ## Install GO dependencies ```shell GO111MODULE=on go get -v golang.org/x/tools/gopls@latest GO111MODULE=on CGO_ENABLED=0 go get -v -trimpath -ldflags '-s -w' github.com/golangci/golangci-lint/cmd/golangci-lint go get -u -v golang.org/x/tools/cmd/godoc go get -u -v golang.org/x/tools/cmd/goimports go get -u -v golang.org/x/tools/cmd/gorename go get -u -v golang.org/x/tools/cmd/guru go get -u -v github.com/cweill/gotests/... go get -u -v github.com/davidrjenni/reftools/cmd/fillstruct go get -u -v github.com/fatih/gomodifytags go get -u -v github.com/godoctor/godoctor go get -u -v github.com/haya14busa/gopkgs/cmd/gopkgs go get -u -v github.com/josharian/impl go get -u -v github.com/rogpeppe/godef ```
164583b54a7d3a8b245cdc8ace40d0ceeff7cb15
[ "TOML", "Markdown", "Shell" ]
4
Shell
luanngominh/dot-files
e8a485dd5caae331fe66c43ca2034f8948a1a7be
c44dfed72c5724c6ad5edee9b1122f0b35a238d1
refs/heads/master
<repo_name>crumped/sheduler<file_sep>/README.md # sheduler The project resolving Nurse scheduling problem. # Shifts -day -night -morning -afternoon # Conditions included in project *soon* <file_sep>/api/views.py from django.shortcuts import render import openpyxl import random import datetime import calendar from math import ceil import copy # TODO # dokładniej sprawdzać dni def index(request): if "GET" == request.method: return render(request, 'api/index.html', {}) else: excel_file = request.FILES["excel_file"] wb = openpyxl.load_workbook(excel_file, data_only=True) worksheet = wb["Arkusz1"] worksheet2 = wb["Arkusz2"] worksheet3 = wb["Arkusz3"] excel_data = list() excel_data_holiday = {} excel_data_cannot_work = {} for index, row in enumerate(worksheet2.iter_rows(), start=0): excel_data_holiday[str(row[0].value)] = [] for index2, cell in enumerate(row, start=0): if index2 != 0: excel_data_holiday[str(row[0].value)].append(cell.value) for index, row in enumerate(worksheet3.iter_rows(), start=0): excel_data_cannot_work[str(row[0].value)] = [] for index2, cell in enumerate(row, start=0): if index2 != 0: excel_data_cannot_work[str(row[0].value)].append(cell.value) # print(excel_data_holiday) today = datetime.datetime.today() month, year = next_mouth(today.month, today.year) num_days = calendar.monthrange(year, month)[1] days = [{"day": datetime.date(year, month, day), "day_name": day, "users_morning": [], "users_day": [], "users_night": [], "users_afternoon": [], "holidays": [], "cannot_work": []} for day in range(1, num_days + 1)] create_data(excel_data, worksheet, days, excel_data_holiday) while True: print("==========================================================================================================") print("========================================== Reset =====================================================") print("==========================================================================================================") users = copy.deepcopy(excel_data) days_tmp = copy.deepcopy(days) get_schedule(days_tmp, users, excel_data_holiday, excel_data_cannot_work) make_up_all_days(days_tmp, users, excel_data_holiday, excel_data_cannot_work) make_up_all_mornings(days_tmp, users, excel_data_holiday, excel_data_cannot_work) print("days_tmp") print(days_tmp) print("users") print(users) if check_data(users): excel_data = users days = days_tmp break representant = representant_data(days, users) # print(days) # print(excel_data) # print(users) return render(request, 'api/index.html', {"excel_data": excel_data, "days": days, "representant": representant}) def representant_data(days, users): representant = [] users_data = users.copy() users_data.pop(0) for i, user in enumerate(users_data, start=0): day_list = [user['user_id'], user['username']] for j, day in enumerate(days, start=0): if int(user['user_id']) in day['users_day']: day_list.append("D") elif int(user['user_id']) in day['users_night']: day_list.append("N") elif int(user['user_id']) in day['users_afternoon']: day_list.append("Płd") elif int(user['user_id']) in day['users_morning']: day_list.append("Ra") elif int(user['user_id']) in day['holidays']: day_list.append("U") elif int(user['user_id']) in day['cannot_work']: day_list.append("X") else: day_list.append(" ") representant.append(day_list) return representant def check_data(users): users_data = users.copy() users_data.pop(0) for user in users_data: if user['month'] != user['total_hours'] or user['12'] != int(user['total_hours'] / 12): return False decimal = user['total_hours'] / 12 number = round(decimal, 2) number_dec = float(str(number - int(number))[1:]) if round(number_dec, 2) == 0.67: if user['8'] != 1: return False if round(number_dec, 2) == 0.33: if user['4'] != 1: return False return True def check_8or4(users): users_data = users.copy() users_data.pop(0) for user in users_data: decimal = user['total_hours'] / 12 number = round(decimal, 2) number_dec = float(str(number - int(number))[1:]) if round(number_dec, 2) == 0.67: if user['8'] != 1: return False if round(number_dec, 2) == 0.33: if user['4'] != 1: return False return True def check_12(users): users_data = users.copy() users_data.pop(0) for user in users_data: if user['12'] != int(user['total_hours'] / 12): return False return True def create_data(excel_data, worksheet, days, holidays): for index, row in enumerate(worksheet.iter_rows(), start=0): row_data = list() if index == 0: row_data.append('Lp') for cell in row: row_data.append(str(cell.value)) else: weeks = {} if row[0].value in holidays: total_time = (int(row[1].value) - (8 * len(holidays[row[0].value]))) else: total_time = row[1].value row_data = {"user_id": str(index), "username": row[0].value, "total_hours": total_time, "month": 0, "12": 0, "8": 0, "4": 0} for day in days: week = week_of_month(day['day']) if week not in weeks: weeks[week] = 0 row_data['weeks'] = weeks excel_data.append(row_data) def week_of_month(dt): """ Returns the week of the month for the specified date. """ first_day = dt.replace(day=1) dom = dt.day adjusted_dom = dom + first_day.weekday() return int(ceil(adjusted_dom / 7.0)) def next_mouth(month, year): if month == 12: year = year + 1 month = 1 else: month = month + 1 return month, year def get_nights(day, i, days, users, available_users): users_last_night = [] users_id_hours = check_user_hours(available_users, day, 12) if i != 0: users_last_night = days[i - 1]['users_night'] users_id = list(set(users_last_night) | set(users_id_hours)) delete_user(available_users, users_id) users_id = [] if len(available_users) > 2: random_numbers = random.sample(range(0, len(available_users)), 3) week = week_of_month(day['day']) for number in random_numbers: user_id = int(available_users[number]["user_id"]) users_id.append(user_id) users[user_id]['weeks'][week] = users[user_id]['weeks'][week] + 12 users[user_id]['month'] = users[user_id]['month'] + 12 users[user_id]['12'] = users[user_id]['12'] + 1 days[i]['users_night'] = users_id def get_days(day, i, days, users, available_users): users_id_hours = check_user_hours(available_users, day, 12) if i != 0: users_id = day['users_night'] + days[i - 1]['users_night'] + days[i - 1]['users_afternoon'] users_b = [] users_c = [] users_f = [] if i < len(days) - 2: users_c = get_workers(days[i - 1], days[i + 1]) if i < len(days) - 3: users_f = get_workers(days[i + 1], days[i + 2]) if i > 1: users_b = get_workers(days[i - 1], days[i - 2]) users_id = list(set(users_id) | set(users_b) | set(users_c) | set(users_f)) else: users_id = day['users_night'] users_b = get_workers(days[i + 1], days[i + 2]) users_id = list(set(users_id) | set(users_b)) users_id = list(set(users_id) | set(users_id_hours)) delete_user(available_users, users_id) users_id = [] if len(available_users) > 2: random_numbers = random.sample(range(0, len(available_users)), 3) week = week_of_month(day['day']) for number in random_numbers: user_id = int(available_users[number]["user_id"]) users_id.append(user_id) users[user_id]['weeks'][week] = users[user_id]['weeks'][week] + 12 users[user_id]['month'] = users[user_id]['month'] + 12 users[user_id]['12'] = users[user_id]['12'] + 1 days[i]["users_day"] = users_id def get_afternoons(day, i, days, users, available_users): users_afternoons = [] if day['day'].weekday() == 1 or day['day'].weekday() == 4: users_id_hours = check_user_8_4_hours(available_users, day) if i != 0: users_id = day['users_night'] + days[i - 1]['users_night'] + day['users_day'] + days[i + 1]['users_day'] else: users_id = day['users_night'] + day['users_day'] + days[i + 1]['users_day'] users_id = list(set(users_id) | set(users_id_hours)) delete_user(available_users, users_id) users_id = [] if len(available_users) > 2: random_numbers = random.sample(range(0, len(available_users)), 1) week = week_of_month(day['day']) for number in random_numbers: user_id = int(available_users[number]["user_id"]) users_id.append(user_id) decimal = users[user_id]['total_hours'] / 12 number = round(decimal, 2) number_dec = float(str(number - int(number))[1:]) if round(number_dec, 2) == 0.67: users[user_id]['weeks'][week] = users[user_id]['weeks'][week] + 8 users[user_id]['month'] = users[user_id]['month'] + 8 users[user_id]['8'] = users[user_id]['8'] + 1 if round(number_dec, 2) == 0.33: users[user_id]['weeks'][week] = users[user_id]['weeks'][week] + 4 users[user_id]['month'] = users[user_id]['month'] + 4 users[user_id]['4'] = users[user_id]['4'] + 1 users_afternoons.append(user_id) days[i]["users_afternoon"] = users_id else: days[i]["users_afternoon"] = [] def delete_user(users, indexes): array_indexes = [] for i in range(len(users)): if int(users[i]['user_id']) in indexes: array_indexes.append(i) for index in sorted(array_indexes, reverse=True): del users[index] def check_user_hours(users, day, number, is_not_enought=False): users_id = [] for i, user in enumerate(users, start=0): week = week_of_month(day['day']) if is_not_enought: max_lim = 48 else: max_lim = 42 if user['weeks'][week] + number > max_lim: users_id.append(int(user['user_id'])) if user['month'] + number > user['total_hours']: if int(user['user_id']) not in users_id: users_id.append(int(user['user_id'])) return users_id def check_user_8_4_hours(users, day, is_not_enought=False): users_id = [] for i, user in enumerate(users, start=0): decimal = user['total_hours'] / 12 number = round(decimal, 2) number_dec = float(str(number - int(number))[1:]) if number_dec == 0.0: users_id.append(int(user['user_id'])) if round(number_dec, 2) == 0.67: if user['8'] == 1: users_id.append(int(user['user_id'])) week = week_of_month(day['day']) if is_not_enought: max_lim = 48 else: max_lim = 42 if user['weeks'][week] + 8 > max_lim: users_id.append(int(user['user_id'])) if user['month'] + 8 > user['total_hours']: if int(user['user_id']) not in users_id: users_id.append(int(user['user_id'])) if round(number_dec, 2) == 0.33: if user['4'] == 1: users_id.append(int(user['user_id'])) week = week_of_month(day['day']) if is_not_enought: max_lim = 48 else: max_lim = 42 if user['weeks'][week] + 4 > max_lim: users_id.append(int(user['user_id'])) if user['month'] + 4 > user['total_hours']: if int(user['user_id']) not in users_id: users_id.append(int(user['user_id'])) return users_id def get_schedule(days, users, holidays, cannot_work): for i, day in enumerate(days, start=0): users_data = users.copy() users_data.pop(0) available_users = users_data.copy() #TODO delete users from available users list for that day user_id = [] for key in holidays: if day['day_name'] in holidays[key]: for user in available_users: if user['username'] == key: user_id.append(int(user['user_id'])) if int(user['user_id']) not in days[i]['holidays']: days[i]['holidays'].append(int(user['user_id'])) for key in cannot_work: if day['day_name'] in cannot_work[key]: for user in available_users: if user['username'] == key: user_id.append(int(user['user_id'])) if int(user['user_id']) not in days[i]['cannot_work']: days[i]['cannot_work'].append(int(user['user_id'])) delete_user(available_users, user_id) get_nights(day, i, days, users, available_users) get_days(day, i, days, users, available_users) get_afternoons(day, i, days, users, available_users) print("days") print(days) def make_up_all_days(days, users, holidays, cannot_work): rols = 0 while not check_12(users): rols = rols + 1 if rols == 100: break for i, day in enumerate(days, start=0): if day['day'].weekday() != 5 or day['day'].weekday() != 6: users_id = [] users_data = users.copy() users_data.pop(0) available_users = users_data.copy() # TODO delete users from available users list for that day holidays_user_id = [] for key in holidays: if day['day_name'] in holidays[key]: for user in available_users: if user['username'] == key: holidays_user_id.append(int(user['user_id'])) if int(user['user_id']) not in days[i]['holidays']: days[i]['holidays'].append(int(user['user_id'])) for key in cannot_work: if day['day_name'] in cannot_work[key]: for user in available_users: if user['username'] == key: holidays_user_id.append(int(user['user_id'])) if int(user['user_id']) not in days[i]['cannot_work']: days[i]['cannot_work'].append(int(user['user_id'])) users_delete_id = find_completed_users(available_users) if rols > 50: users_id_hours = check_user_hours(available_users, day, 12) else: users_id_hours = check_user_hours(available_users, day, 12, True) if i == 0: users_id = day['users_night'] + day['users_day'] + day['users_afternoon'] users_b = get_workers(days[i + 1], days[i + 2]) users_id = list(set(users_id) | set(users_b)) else: users_id = day['users_night'] + days[i - 1]['users_night'] + day['users_day']\ + day['users_afternoon'] + days[i - 1]['users_afternoon'] users_b = [] users_c = [] users_f = [] if i < len(days) - 2: users_c = get_workers(days[i - 1], days[i + 1]) if i < len(days) - 3: users_f = get_workers(days[i + 1], days[i + 2]) if i > 1: users_b = get_workers(days[i - 1], days[i - 2]) users_id = list(set(users_id) | set(users_b) | set(users_c) | set(users_f)) users_id = list(set(users_id) | set(users_delete_id) | set(users_id_hours) | set(holidays_user_id)) delete_user(available_users, users_id) if len(available_users) > 0: number = random.randint(0, len(available_users) - 1) week = week_of_month(day['day']) user_id = int(available_users[number]["user_id"]) users[user_id]['weeks'][week] = users[user_id]['weeks'][week] + 12 users[user_id]['month'] = users[user_id]['month'] + 12 users[user_id]['12'] = users[user_id]['12'] + 1 days[i]["users_day"].append(user_id) def make_up_all_mornings(days, users, holidays, cannot_work): rols = 0 while not check_8or4(users): rols = rols + 1 if rols == 100: break for i, day in enumerate(days, start=0): if day['day'].weekday() == 0 or day['day'].weekday() == 2 or day['day'].weekday() == 3: users_id = [] users_data = users.copy() users_data.pop(0) available_users = users_data.copy() # TODO delete users from available users list for that day holidays_user_id = [] for key in holidays: if day['day_name'] in holidays[key]: for user in available_users: if user['username'] == key: holidays_user_id.append(int(user['user_id'])) if int(user['user_id']) not in days[i]['holidays']: days[i]['holidays'].append(int(user['user_id'])) for key in cannot_work: if day['day_name'] in cannot_work[key]: for user in available_users: if user['username'] == key: holidays_user_id.append(int(user['user_id'])) if int(user['user_id']) not in days[i]['cannot_work']: days[i]['cannot_work'].append(int(user['user_id'])) # delete_user(available_users, holidays_user_id) if rols > 50: users_id_hours = check_user_8_4_hours(available_users, day) else: users_id_hours = check_user_8_4_hours(available_users, day, True) if i == 0: users_id = day['users_night'] + day['users_day'] + day['users_afternoon'] users_b = get_workers(days[i + 1], days[i + 2]) users_id = list(set(users_id) | set(users_b)) else: users_id = day['users_night'] + days[i - 1]['users_night'] + day['users_day'] + day['users_afternoon'] + days[i - 1]['users_afternoon'] users_b = [] users_c = [] users_f = [] if i < len(days) - 2: users_c = get_workers(days[i - 1], days[i + 1]) if i < len(days) - 3: users_f = get_workers(days[i + 1], days[i + 2]) if i > 1: users_b = get_workers(days[i - 1], days[i - 2]) users_id = list(set(users_id) | set(users_b) | set(users_c) | set(users_f)) users_id = list(set(users_id) | set(users_id_hours) | set(holidays_user_id)) delete_user(available_users, users_id) print("available_users") print(available_users) if len(available_users) > 0: number = random.randint(0, len(available_users) - 1) week = week_of_month(day['day']) user_id = int(available_users[number]["user_id"]) decimal = users[user_id]['total_hours'] / 12 number = round(decimal, 2) number_dec = float(str(number - int(number))[1:]) if round(number_dec, 2) == 0.67: users[user_id]['weeks'][week] = users[user_id]['weeks'][week] + 8 users[user_id]['month'] = users[user_id]['month'] + 8 users[user_id]['8'] = users[user_id]['8'] + 1 if round(number_dec, 2) == 0.33: users[user_id]['weeks'][week] = users[user_id]['weeks'][week] + 4 users[user_id]['month'] = users[user_id]['month'] + 4 users[user_id]['4'] = users[user_id]['4'] + 1 days[i]["users_morning"] = [user_id] def get_workers(day_1, day_2): return set(day_1['users_day']) - (set(day_1['users_day']) - set(day_2['users_day'])) # return set(part) - (set(part) - set(day_2['users_afternoon'])) def find_completed_users(users): users_id = [] for user in users: if user['12'] == int(user['total_hours'] / 12): users_id.append(int(user['user_id'])) return users_id
be3937a9d917cba53a0f373657feed0096a7b194
[ "Markdown", "Python" ]
2
Markdown
crumped/sheduler
e9519679c0477fae3ed5a30cd3bee27bbf6e89b8
fadc452843a9d4780c60ec5ecdb7c0d0b4e8f5a1
refs/heads/master
<file_sep>#!/bin/bash docker build -t carlochess/mozart2 . <file_sep>FROM ubuntu:14.04 MAINTAINER <NAME> <<EMAIL>> RUN apt-get update RUN apt-get install -y software-properties-common python-software-properties RUN add-apt-repository ppa:ubuntu-toolchain-r/test -y RUN apt-get update RUN apt-get install -y libboost-all-dev tk8.5-dev emacs23-nox subversion cmake git python libxml2-dev default-jre make RUN mkdir externals WORKDIR /externals RUN git clone https://github.com/stp/googletest.git gtest RUN svn co --quiet http://llvm.org/svn/llvm-project/llvm/tags/RELEASE_33/final llvm WORKDIR /externals/llvm/tools/ RUN svn co --quiet http://llvm.org/svn/llvm-project/cfe/tags/RELEASE_33/final clang RUN cd ../../.. && mkdir builds && cd builds && mkdir gtest-debug WORKDIR /builds/gtest-debug RUN cmake -DCMAKE_BUILD_TYPE=Debug ../../externals/gtest RUN make -j4 RUN cd .. && mkdir llvm-release WORKDIR /builds/llvm-release RUN cmake -DCMAKE_BUILD_TYPE=Release ../../externals/llvm RUN make -j4 WORKDIR / RUN git clone --recursive https://github.com/dianacgr/mozart2.git RUN cd builds && mkdir mozart2-release WORKDIR /builds/mozart2-release RUN cmake -DCMAKE_BUILD_TYPE=Release -DGTEST_SRC_DIR=../../externals/gtest -DGTEST_BUILD_DIR=../gtest-debug -DLLVM_SRC_DIR=../../externals/llvm -DLLVM_BUILD_DIR=../llvm-release ../../mozart2 RUN make RUN make install RUN rm -rf /externals /builds /mozart2 RUN apt-get clean RUN rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* RUN useradd -ms /bin/bash mozart RUN echo mozart:mozart | chpasswd RUN adduser mozart sudo ENV PATH="$PATH:/usr/local/bin/oz:" WORKDIR /home/mozart ADD helloworld.oz . RUN chown mozart:mozart helloworld.oz USER mozart CMD bash <file_sep># Mozart2Docker Docker image for Mozart 2 programming language # Create image ``` docker build -t carlochess/mozart2 . ``` # Run ``` docker run -it carlochess/mozart2 /bin/bash ```
bf22081e0c769019efa9b3b0ad9871df2a10d813
[ "Markdown", "Dockerfile", "Shell" ]
3
Shell
carlochess/Mozart2Docker
a0e5f6f6a1ee10b3e97e09b836ed442775d22ba0
c100fcaf6e9f20dd9149a29a3a13127036edc74b