CCMain.m 232 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420
  1. //
  2. // CCMain.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotos.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "JDStatusBarNotification.h"
  35. #import "NCAutoUpload.h"
  36. #import "NCEndToEndEncryption.h"
  37. #import "NCBridgeSwift.h"
  38. #import "NYMnemonic.h"
  39. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate, UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, CCLoginDelegate, CCLoginDelegateWeb>
  40. {
  41. tableMetadata *_metadata;
  42. BOOL _isRoot;
  43. BOOL _isViewDidLoad;
  44. BOOL _isSelectedMode;
  45. NSMutableDictionary *_selectedFileIDsMetadatas;
  46. NSUInteger _numSelectedFileIDsMetadatas;
  47. NSMutableArray *_queueSelector;
  48. NSMutableDictionary *_statusSwipeCell;
  49. UIImageView *_ImageTitleHomeCryptoCloud;
  50. UIView *_reMenuBackgroundView;
  51. UITapGestureRecognizer *_singleFingerTap;
  52. NSString *_directoryGroupBy;
  53. NSString *_directoryOrder;
  54. NSUInteger _failedAttempts;
  55. NSDate *_lockUntilDate;
  56. NSString *_fatherPermission;
  57. UIRefreshControl *_refreshControl;
  58. UIDocumentInteractionController *_docController;
  59. CCHud *_hud;
  60. CCHud *_hudDeterminate;
  61. // Datasource
  62. CCSectionDataSourceMetadata *_sectionDataSource;
  63. NSDate *_dateReadDataSource;
  64. // Search
  65. BOOL _isSearchMode;
  66. NSString *_searchFileName;
  67. NSMutableArray *_searchResultMetadatas;
  68. NSString *_noFilesSearchTitle;
  69. NSString *_noFilesSearchDescription;
  70. NSTimer *_timerWaitInput;
  71. // Login
  72. CCLoginWeb *_loginWeb;
  73. CCLogin *_loginVC;
  74. BOOL _loadingFolder;
  75. }
  76. @end
  77. @implementation CCMain
  78. #pragma --------------------------------------------------------------------------------------------
  79. #pragma mark ===== Init =====
  80. #pragma --------------------------------------------------------------------------------------------
  81. - (id)initWithCoder:(NSCoder *)aDecoder
  82. {
  83. if (self = [super initWithCoder:aDecoder]) {
  84. _directoryOrder = [CCUtility getOrderSettings];
  85. _directoryGroupBy = [CCUtility getGroupBySettings];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  90. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  91. }
  92. return self;
  93. }
  94. #pragma --------------------------------------------------------------------------------------------
  95. #pragma mark ===== View =====
  96. #pragma --------------------------------------------------------------------------------------------
  97. - (void)viewDidLoad
  98. {
  99. [super viewDidLoad];
  100. // init object
  101. _metadata = [tableMetadata new];
  102. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  104. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  105. _statusSwipeCell = [NSMutableDictionary new];
  106. _queueSelector = [NSMutableArray new];
  107. _isViewDidLoad = YES;
  108. _fatherPermission = @"";
  109. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  110. _searchResultMetadatas = [NSMutableArray new];
  111. _searchFileName = @"";
  112. _noFilesSearchTitle = @"";
  113. _noFilesSearchDescription = @"";
  114. // delegate
  115. self.tableView.delegate = self;
  116. self.tableView.tableFooterView = [UIView new];
  117. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  118. self.tableView.emptyDataSetDelegate = self;
  119. self.tableView.emptyDataSetSource = self;
  120. self.searchController.delegate = self;
  121. self.searchController.searchBar.delegate = self;
  122. [CCNetworking sharedNetworking].delegate = self;
  123. // Custom Cell
  124. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  125. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  126. // long press recognizer TableView
  127. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  128. [self.tableView addGestureRecognizer:longPressRecognizer];
  129. // Pull-to-Refresh
  130. [self createRefreshControl];
  131. // Register for 3D Touch Previewing if available
  132. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  133. {
  134. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  135. }
  136. // Back Button
  137. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  138. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  139. // reMenu Background
  140. _reMenuBackgroundView = [[UIView alloc] init];
  141. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  142. // if this is not Main (the Main uses inizializeMain)
  143. if (_isRoot == NO && app.activeAccount.length > 0) {
  144. // Settings this folder & delegate & Loading datasource
  145. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  146. // Load Datasource
  147. [self reloadDatasource:_serverUrl];
  148. // Read (File) Folder
  149. [self readFileReloadFolder];
  150. }
  151. // Title
  152. [self setTitle];
  153. // Search
  154. self.definesPresentationContext = YES;
  155. self.searchController.searchResultsUpdater = self;
  156. self.searchController.dimsBackgroundDuringPresentation = NO;
  157. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  158. [self.searchController.searchBar sizeToFit];
  159. self.searchController.searchBar.delegate = self;
  160. if (@available(iOS 11, *)) {
  161. self.navigationItem.searchController = self.searchController;
  162. self.navigationItem.hidesSearchBarWhenScrolling = true;
  163. self.navigationItem.searchController.searchBar.tintColor = [UIColor whiteColor];
  164. UITextField *textField = [self.searchController.searchBar valueForKey:@"searchField"];
  165. textField.textColor = [UIColor blackColor];
  166. textField.tintColor = [UIColor blackColor];
  167. UIView *backgroundView = textField.subviews.firstObject;
  168. backgroundView.backgroundColor = UIColor.whiteColor;
  169. backgroundView.layer.cornerRadius = 10;
  170. backgroundView.clipsToBounds = YES;
  171. } else {
  172. self.tableView.tableHeaderView = self.searchController.searchBar;
  173. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  174. }
  175. }
  176. // Apparirà
  177. - (void)viewWillAppear:(BOOL)animated
  178. {
  179. [super viewWillAppear:animated];
  180. // test
  181. if (app.activeAccount.length == 0)
  182. return;
  183. // Settings this folder & delegate & Loading datasource
  184. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  185. [CCNetworking sharedNetworking].delegate = self;
  186. // Color
  187. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  188. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  189. if (_isSelectedMode)
  190. [self setUINavigationBarSelected];
  191. else
  192. [self setUINavigationBarDefault];
  193. // If not editing mode remove _selectedFileIDs
  194. if (!self.tableView.editing)
  195. [_selectedFileIDsMetadatas removeAllObjects];
  196. // Plus Button
  197. [app plusButtonVisibile:true];
  198. }
  199. // E' arrivato
  200. - (void)viewDidAppear:(BOOL)animated
  201. {
  202. [super viewDidAppear:animated];
  203. // Active Main
  204. app.activeMain = self;
  205. // Test viewDidLoad
  206. if (_isViewDidLoad) {
  207. _isViewDidLoad = NO;
  208. } else {
  209. if (app.activeAccount.length > 0 && [_selectedFileIDsMetadatas count] == 0) {
  210. // Load Datasource
  211. [self reloadDatasource:_serverUrl];
  212. // Read (file) Folder
  213. [self readFileReloadFolder];
  214. }
  215. }
  216. // Title
  217. [self setTitle];
  218. }
  219. - (void)viewWillDisappear:(BOOL)animated
  220. {
  221. [super viewWillDisappear:animated];
  222. [self closeAllMenu];
  223. }
  224. - (void)didReceiveMemoryWarning
  225. {
  226. [super didReceiveMemoryWarning];
  227. // Dispose of any resources that can be recreated.
  228. }
  229. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  230. {
  231. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  232. [self closeAllMenu];
  233. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  234. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  235. // Portrait
  236. } else {
  237. // Landscape
  238. }
  239. [self.tableView reloadData];
  240. }];
  241. }
  242. - (BOOL)prefersStatusBarHidden
  243. {
  244. return NO;
  245. }
  246. // detect scroll for remove keyboard in search mode
  247. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  248. {
  249. if (_isSearchMode && scrollView == self.tableView) {
  250. [self.searchController.searchBar endEditing:YES];
  251. }
  252. }
  253. - (void)changeTheming
  254. {
  255. if (self.isViewLoaded && self.view.window)
  256. [app changeTheming:self];
  257. // Refresh control
  258. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  259. // Reload Table View
  260. [self tableViewReloadData];
  261. }
  262. #pragma --------------------------------------------------------------------------------------------
  263. #pragma mark ===== Initizlize Mail =====
  264. #pragma --------------------------------------------------------------------------------------------
  265. - (void)initializeMain:(NSNotification *)notification
  266. {
  267. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  268. _directoryGroupBy = nil;
  269. _directoryOrder = nil;
  270. _dateReadDataSource = nil;
  271. // test
  272. if (app.activeAccount.length == 0)
  273. return;
  274. if ([app.listMainVC count] == 0 || _isRoot) {
  275. // This is Root home main add list
  276. appDelegate.homeMain = self;
  277. _isRoot = YES;
  278. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  279. appDelegate.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  280. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  281. // go Home
  282. [self.navigationController popToRootViewControllerAnimated:NO];
  283. // setting Networking
  284. [CCNetworking sharedNetworking].delegate = self;
  285. [[CCNetworking sharedNetworking] settingAccount];
  286. // Remove search mode
  287. [self cancelSearchBar];
  288. // populate shared Link & User
  289. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  290. if (results) {
  291. appDelegate.sharesLink = results[0];
  292. appDelegate.sharesUserAndGroup = results[1];
  293. }
  294. // Load Datasource
  295. [self reloadDatasource:_serverUrl];
  296. // Read (File) Folder
  297. [self readFileReloadFolder];
  298. // Setting Theming
  299. [app settingThemingColorBrand];
  300. // Load photo datasorce
  301. if (appDelegate.activePhotos)
  302. [appDelegate.activePhotos reloadDatasourceForced];
  303. // remove all of detail
  304. if (appDelegate.activeDetail)
  305. [appDelegate.activeDetail removeAllView];
  306. // remove all Notification Messages
  307. [appDelegate.listOfNotifications removeAllObjects];
  308. // Not Photos Video in library ? then align
  309. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", app.activeAccount]];
  310. if ([recordsPhotoLibrary count] == 0) {
  311. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  312. }
  313. // Initializations
  314. [appDelegate applicationInitialized];
  315. } else {
  316. // reload datasource
  317. [self reloadDatasource:_serverUrl];
  318. }
  319. }
  320. #pragma --------------------------------------------------------------------------------------------
  321. #pragma mark ==== DZNEmptyDataSetSource ====
  322. #pragma --------------------------------------------------------------------------------------------
  323. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  324. {
  325. if (_loadingFolder)
  326. return NO;
  327. else
  328. return YES;
  329. }
  330. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  331. {
  332. return [UIColor whiteColor];
  333. }
  334. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  335. {
  336. if (_isSearchMode)
  337. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"searchBig"] color:[NCBrandColor sharedInstance].brand];
  338. else
  339. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  340. }
  341. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  342. {
  343. if (_loadingFolder && _refreshControl.isRefreshing == NO) {
  344. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  345. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  346. activityView.color = [NCBrandColor sharedInstance].brand;
  347. [activityView startAnimating];
  348. return activityView;
  349. }
  350. return nil;
  351. }
  352. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  353. {
  354. NSString *text;
  355. if (_isSearchMode) {
  356. text = _noFilesSearchTitle;
  357. } else {
  358. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  359. }
  360. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  361. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  362. }
  363. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  364. {
  365. NSString *text;
  366. if (_isSearchMode) {
  367. text = _noFilesSearchDescription;
  368. } else {
  369. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  370. }
  371. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  372. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  373. paragraph.alignment = NSTextAlignmentCenter;
  374. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  375. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  376. }
  377. #pragma --------------------------------------------------------------------------------------------
  378. #pragma mark ===== Text Field =====
  379. #pragma --------------------------------------------------------------------------------------------
  380. - (void)minCharTextFieldDidChange:(UITextField *)sender
  381. {
  382. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  383. if (alertController)
  384. {
  385. UITextField *fileName = alertController.textFields.firstObject;
  386. UIAlertAction *okAction = alertController.actions.lastObject;
  387. okAction.enabled = fileName.text.length > 0;
  388. }
  389. }
  390. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  391. [textField selectAll:textField];
  392. }
  393. #pragma --------------------------------------------------------------------------------------------
  394. #pragma mark ===== Graphic Window =====
  395. #pragma --------------------------------------------------------------------------------------------
  396. - (void)createRefreshControl
  397. {
  398. _refreshControl = [UIRefreshControl new];
  399. if (@available(iOS 11.0, *)) {
  400. [self.tableView setRefreshControl:_refreshControl];
  401. _refreshControl.tintColor = [UIColor whiteColor];
  402. } else {
  403. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  404. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  405. [self setRefreshControl:_refreshControl];
  406. }
  407. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  408. }
  409. - (void)deleteRefreshControl
  410. {
  411. [_refreshControl endRefreshing];
  412. self.refreshControl = nil;
  413. }
  414. - (void)refreshControlTarget
  415. {
  416. [self readFolder:_serverUrl];
  417. // Actuate `Peek` feedback (weak boom)
  418. AudioServicesPlaySystemSound(1519);
  419. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  420. }
  421. - (void)setTitle
  422. {
  423. // Color text self.navigationItem.title
  424. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  425. if (_isSelectedMode) {
  426. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  427. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  428. self.navigationItem.titleView = nil;
  429. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  430. } else {
  431. // we are in home : LOGO BRAND
  432. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  433. self.navigationItem.title = nil;
  434. if ([app.reachability isReachable] == NO)
  435. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  436. else
  437. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  438. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  439. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo:)];
  440. [singleTap setNumberOfTapsRequired:1];
  441. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  442. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  443. } else {
  444. self.navigationItem.title = _titleMain;
  445. }
  446. }
  447. }
  448. - (void)setUINavigationBarDefault
  449. {
  450. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  451. UIBarButtonItem *buttonMore, *buttonNotification;
  452. // =
  453. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  454. buttonMore.enabled = true;
  455. // <
  456. self.navigationController.navigationBar.hidden = NO;
  457. // Notification
  458. if ([app.listOfNotifications count] > 0) {
  459. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  460. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  461. buttonNotification.enabled = true;
  462. }
  463. if (buttonNotification)
  464. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  465. else
  466. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  467. self.navigationItem.leftBarButtonItem = nil;
  468. }
  469. - (void)setUINavigationBarSelected
  470. {
  471. [app aspectNavigationControllerBar:self.navigationController.navigationBar online:[app.reachability isReachable] hidden:NO];
  472. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  473. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  474. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  475. self.navigationItem.leftBarButtonItem = leftButton;
  476. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  477. }
  478. - (void)cancelSelect
  479. {
  480. [self tableViewSelect:NO];
  481. [app.reSelectMenu close];
  482. }
  483. - (void)closeAllMenu
  484. {
  485. // close Menu
  486. [app.reSelectMenu close];
  487. [app.reMainMenu close];
  488. // Close Menu Logo
  489. [CCMenuAccount dismissMenu];
  490. }
  491. #pragma --------------------------------------------------------------------------------------------
  492. #pragma mark ===== Document Picker =====
  493. #pragma --------------------------------------------------------------------------------------------
  494. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  495. {
  496. NSLog(@"Cancelled");
  497. }
  498. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  499. {
  500. NSLog(@"Cancelled");
  501. }
  502. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  503. {
  504. documentPicker.delegate = self;
  505. [self presentViewController:documentPicker animated:YES completion:nil];
  506. }
  507. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  508. {
  509. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  510. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  511. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  512. __block NSError *error;
  513. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  514. NSString *fileName = [url lastPathComponent];
  515. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  516. NSData *data = [NSData dataWithContentsOfURL:newURL];
  517. if (data && error == nil) {
  518. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  519. // Upload File
  520. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:serverUrl session:k_upload_session taskStatus: k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  521. } else {
  522. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  523. }
  524. } else {
  525. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  526. }
  527. }];
  528. }
  529. }
  530. - (void)openImportDocumentPicker
  531. {
  532. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  533. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  534. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  535. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  536. documentProviderMenu.delegate = self;
  537. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  538. }
  539. #pragma --------------------------------------------------------------------------------------------
  540. #pragma mark ===== Assets Picker =====
  541. #pragma --------------------------------------------------------------------------------------------
  542. -(void)dismissFormUploadAssets
  543. {
  544. [self reloadDatasource];
  545. }
  546. - (void)openAssetsPickerController
  547. {
  548. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  549. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  550. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  551. //UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil]; // DEPRECATED iOS9
  552. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedInInstancesOfClasses:@[[CTAssetsPickerController class]]];
  553. [app aspectNavigationControllerBar:navBar online:YES hidden:NO];
  554. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  555. dispatch_async(dispatch_get_main_queue(), ^{
  556. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  557. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeBottom];
  558. // init picker
  559. CTAssetsPickerController *picker = [CTAssetsPickerController new];
  560. // set delegate
  561. picker.delegate = self;
  562. // to show selection order
  563. //picker.showsSelectionIndex = YES;
  564. // to present picker as a form sheet in iPad
  565. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  566. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  567. // present picker
  568. [self presentViewController:picker animated:YES completion:nil];
  569. });
  570. }];
  571. }
  572. - (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset
  573. {
  574. if (picker.selectedAssets.count > k_pickerControllerMax) {
  575. [app messageNotification:@"_info_" description:@"_limited_dimension_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  576. return NO;
  577. }
  578. return YES;
  579. }
  580. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  581. {
  582. [picker dismissViewControllerAnimated:YES completion:^{
  583. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  584. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:assets cryptated:NO session:k_upload_session delegate:self];
  585. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  586. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  587. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  588. [self presentViewController:navigationController animated:YES completion:nil];
  589. }];
  590. }
  591. // New folder or new photo or video
  592. - (void)returnCreate:(NSInteger)type
  593. {
  594. switch (type) {
  595. case k_returnCreateFolderPlain: {
  596. NSString *serverUrl = [app getTabBarControllerActiveServerUrl];
  597. NSString *message;
  598. UIAlertController *alertController;
  599. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  600. message = @"/";
  601. } else {
  602. message = [serverUrl lastPathComponent];
  603. }
  604. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  605. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  606. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  607. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  608. }];
  609. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  610. NSLog(@"Cancel action");
  611. }];
  612. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  613. UITextField *fileName = alertController.textFields.firstObject;
  614. [self createFolder:fileName.text serverUrl:serverUrl];
  615. }];
  616. okAction.enabled = NO;
  617. [alertController addAction:cancelAction];
  618. [alertController addAction:okAction];
  619. [self presentViewController:alertController animated:YES completion:nil];
  620. }
  621. break;
  622. case k_returnCreateFotoVideoPlain: {
  623. [self openAssetsPickerController];
  624. }
  625. break;
  626. case k_returnCreateFilePlain: {
  627. [self openImportDocumentPicker];
  628. }
  629. break;
  630. case k_returnCreateFotoVideoEncrypted: {
  631. [self openAssetsPickerController];
  632. }
  633. break;
  634. case k_returnCreateFileEncrypted: {
  635. [self openImportDocumentPicker];
  636. }
  637. break;
  638. case k_returnCreateFileText: {
  639. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"NCText" bundle:nil] instantiateViewControllerWithIdentifier:@"NCText"];
  640. navigationController.modalPresentationStyle = UIModalPresentationPageSheet;
  641. [self presentViewController:navigationController animated:YES completion:nil];
  642. }
  643. break;
  644. }
  645. }
  646. #pragma --------------------------------------------------------------------------------------------
  647. #pragma mark ===== Save selected File =====
  648. #pragma --------------------------------------------------------------------------------------------
  649. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  650. {
  651. if (error)
  652. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  653. else
  654. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  655. }
  656. - (void)saveSelectedFiles
  657. {
  658. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  659. return;
  660. NSLog(@"[LOG] Start download selected files ...");
  661. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  662. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  663. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  664. for (tableMetadata *metadata in metadatas) {
  665. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  666. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  667. if (serverUrl)
  668. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  669. }
  670. }
  671. [_hud hideHud];
  672. });
  673. [self tableViewSelect:NO];
  674. }
  675. #pragma --------------------------------------------------------------------------------------------
  676. #pragma mark === Delegate Login ===
  677. #pragma --------------------------------------------------------------------------------------------
  678. - (void)loginSuccess:(NSInteger)loginType
  679. {
  680. [self readFolder:_serverUrl];
  681. }
  682. - (void)loginDisappear
  683. {
  684. app.activeLogin = nil;
  685. }
  686. #pragma mark -
  687. #pragma --------------------------------------------------------------------------------------------
  688. #pragma mark ===== Peek & Pop =====
  689. #pragma --------------------------------------------------------------------------------------------
  690. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  691. {
  692. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  693. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  694. if (metadata.thumbnailExists) {
  695. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  696. if (cell) {
  697. previewingContext.sourceRect = cell.frame;
  698. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  699. vc.delegate = self;
  700. vc.metadata = metadata;
  701. return vc;
  702. }
  703. }
  704. return nil;
  705. }
  706. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  707. {
  708. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  709. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  710. }
  711. #pragma mark -
  712. #pragma --------------------------------------------------------------------------------------------
  713. #pragma mark ==== External Sites ====
  714. #pragma --------------------------------------------------------------------------------------------
  715. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  716. {
  717. [[NCManageDatabase sharedInstance] deleteExternalSites];
  718. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  719. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  720. }
  721. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  722. {
  723. NSString *error = [NSString stringWithFormat:@"Get external site failure error %lu, %@", (long)errorCode, message];
  724. NSLog(@"[LOG] %@", error);
  725. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get External Sites Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  726. }
  727. #pragma --------------------------------------------------------------------------------------------
  728. #pragma mark ==== Activity ====
  729. #pragma --------------------------------------------------------------------------------------------
  730. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  731. {
  732. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  733. // Reload Activity Data Source
  734. [app.activeActivity reloadDatasource];
  735. }
  736. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  737. {
  738. NSString *error = [NSString stringWithFormat:@"Get Activity Server failure error %lu, %@", (long)errorCode, message];
  739. NSLog(@"[LOG] %@", error);
  740. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Activity Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  741. }
  742. #pragma --------------------------------------------------------------------------------------------
  743. #pragma mark ==== Notification ====
  744. #pragma --------------------------------------------------------------------------------------------
  745. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  746. {
  747. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  748. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  749. // Order by date
  750. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  751. OCNotifications *notification1 = obj1, *notification2 = obj2;
  752. return [notification2.date compare: notification1.date];
  753. }];
  754. // verify if listOfNotifications is changed
  755. NSString *old = @"", *new = @"";
  756. for (OCNotifications *notification in listOfNotifications)
  757. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  758. for (OCNotifications *notification in appDelegate.listOfNotifications)
  759. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  760. if (![new isEqualToString:old]) {
  761. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  762. // reload Notification view
  763. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"notificationReloadData" object:nil];
  764. }
  765. // Update NavigationBar
  766. if (!_isSelectedMode) {
  767. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  768. }
  769. });
  770. }
  771. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  772. {
  773. NSString *error = [NSString stringWithFormat:@"Get Notification Server failure error %lu, %@", (long)errorCode, message];
  774. NSLog(@"[LOG] %@", error);
  775. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Notification Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  776. // Update NavigationBar
  777. if (!_isSelectedMode)
  778. [self setUINavigationBarDefault];
  779. }
  780. - (void)viewNotification
  781. {
  782. if ([app.listOfNotifications count] > 0) {
  783. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  784. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  785. [self presentViewController:notificationVC animated:YES completion:nil];
  786. }
  787. }
  788. #pragma --------------------------------------------------------------------------------------------
  789. #pragma mark ==== User Profile ====
  790. #pragma --------------------------------------------------------------------------------------------
  791. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  792. {
  793. NSString *error = [NSString stringWithFormat:@"Get user profile failure error %lu, %@", (long)errorCode, message];
  794. NSLog(@"[LOG] %@", error);
  795. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get user profile Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  796. }
  797. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  798. {
  799. // Update User (+ userProfile.id)
  800. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  801. // Get Account Active
  802. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  803. // Setting App active account
  804. [app settingActiveAccount:account.account activeUrl:account.url activeUser:account.user activeUserID:account.userID activePassword:account.password];
  805. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  806. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  807. //UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  808. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  809. if (avatar)
  810. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  811. else
  812. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  813. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"changeUserProfile" object:nil];
  814. });
  815. }
  816. #pragma --------------------------------------------------------------------------------------------
  817. #pragma mark ==== Capabilities ====
  818. #pragma --------------------------------------------------------------------------------------------
  819. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  820. {
  821. // Unauthorized
  822. if (errorCode == kOCErrorServerUnauthorized)
  823. [app openLoginView:self loginType:loginModifyPasswordUser];
  824. NSString *error = [NSString stringWithFormat:@"Get Capabilities failure error %lu, %@", (long)errorCode, message];
  825. NSLog(@"[LOG] %@", error);
  826. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionCapabilities selector:@"Get Capabilities of Server" note:error type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  827. // Change Theming color
  828. [app settingThemingColorBrand];
  829. }
  830. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  831. {
  832. // Update capabilities db
  833. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  834. // ------ THEMING -----------------------------------------------------------------------
  835. // Download Theming Background & Change Theming color
  836. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  837. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  838. //UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]]; DEPRECATED iOS9
  839. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]]]];
  840. if (themingBackground)
  841. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  842. else
  843. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  844. }
  845. dispatch_async(dispatch_get_main_queue(), ^{
  846. [app settingThemingColorBrand];
  847. });
  848. });
  849. // ------ SEARCH ------------------------------------------------------------------------
  850. // Search bar if change version
  851. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  852. [self cancelSearchBar];
  853. }
  854. // ------ GET SERVICE SERVER ------------------------------------------------------------
  855. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  856. // Read External Sites
  857. if (capabilities.isExternalSitesServerEnabled) {
  858. metadataNet.action = actionGetExternalSitesServer;
  859. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  860. }
  861. // Read Share
  862. if (capabilities.isFilesSharingAPIEnabled) {
  863. [app.sharesID removeAllObjects];
  864. metadataNet.action = actionReadShareServer;
  865. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  866. }
  867. // Read Notification
  868. metadataNet.action = actionGetNotificationServer;
  869. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  870. // Read User Profile
  871. metadataNet.action = actionGetUserProfile;
  872. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  873. // Read Activity
  874. metadataNet.action = actionGetActivityServer;
  875. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  876. // Get End-To-End PrivateKey (if enabled)
  877. if (capabilities.isEndToEndEncryptionEnabled) {
  878. metadataNet.action = actionGetEndToEndPublicKey;
  879. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  880. metadataNet.action = actionGetEndToEndPrivateKey;
  881. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  882. }
  883. }
  884. #pragma mark -
  885. #pragma --------------------------------------------------------------------------------------------
  886. #pragma mark ==== Request Server Information ====
  887. #pragma --------------------------------------------------------------------------------------------
  888. - (void)requestServerCapabilities
  889. {
  890. // test
  891. if (app.activeAccount.length == 0)
  892. return;
  893. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  894. metadataNet.action = actionGetCapabilities;
  895. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  896. }
  897. #pragma mark -
  898. #pragma --------------------------------------------------------------------------------------------
  899. #pragma mark ==== Middleware Ping ====
  900. #pragma --------------------------------------------------------------------------------------------
  901. - (void)middlewarePing
  902. {
  903. // test
  904. if (app.activeAccount.length == 0)
  905. return;
  906. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  907. metadataNet.action = actionMiddlewarePing;
  908. metadataNet.serverUrl = [[NCBrandOptions sharedInstance] middlewarePingUrl];
  909. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  910. }
  911. #pragma mark -
  912. #pragma --------------------------------------------------------------------------------------------
  913. #pragma mark ==== End-to-End Encryption ====
  914. #pragma --------------------------------------------------------------------------------------------
  915. // ++++++++++++++++++++++ PUBLIC KEY ++++++++++++++++++++++
  916. - (void)getEndToEndPublicKeySuccess:(CCMetadataNet *)metadataNet
  917. {
  918. // Activity
  919. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:@"EndToEndPublicKey present on Server" type:k_activityTypeSuccess verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  920. #ifdef DEBUG
  921. [app messageNotification:@"Get E2E PublicKey" description:@"Success" visible:YES delay:1 type:TWMessageBarMessageTypeSuccess errorCode:0];
  922. #endif
  923. }
  924. - (void)getEndToEndPublicKeyFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  925. {
  926. switch (errorCode) {
  927. case 400:
  928. message = @"bad request: unpredictable internal error";
  929. [app messageNotification:@"E2E public key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  930. break;
  931. case 404: {
  932. // remove keychain
  933. [CCUtility setEndToEndPublicKey:app.activeUser publicKey:metadataNet.options];
  934. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  935. NSString *publicKeyEncoded = [[NCEndToEndEncryption sharedManager] createEndToEndPublicKey:app.activeUserID directoryUser:app.directoryUser];
  936. if (publicKeyEncoded) {
  937. metadataNet.action = actionStoreEndToEndPublicKey;
  938. metadataNet.options = publicKeyEncoded;
  939. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  940. } else {
  941. // Activity
  942. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:@"Error to create PublicKeyEncoded" type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  943. }
  944. message = @"public keys couldn't be found";
  945. }
  946. break;
  947. case 409:
  948. message = @"forbidden: the user can't access the public key";
  949. [app messageNotification:@"E2E public key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  950. break;
  951. default:
  952. [app messageNotification:@"E2E public key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  953. break;
  954. }
  955. // Activity
  956. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:message type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  957. }
  958. - (void)storeEndToEndPublicKeySuccess:(CCMetadataNet *)metadataNet
  959. {
  960. // Store signed key locally keychain
  961. [CCUtility setEndToEndPublicKey:app.activeUser publicKey:metadataNet.options];
  962. // Activity
  963. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:@"EndToEndPublicKey stored on Server and stored locally" type:k_activityTypeSuccess verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  964. #ifdef DEBUG
  965. [app messageNotification:@"Store E2E PublicKey" description:@"Success" visible:YES delay:1 type:TWMessageBarMessageTypeSuccess errorCode:0];
  966. #endif
  967. }
  968. - (void)storeEndToEndPublicKeyFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  969. {
  970. [app messageNotification:@"E2E sign public key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  971. // Activity
  972. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:message type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  973. }
  974. - (void)deleteEndToEndPublicKeySuccess:(CCMetadataNet *)metadataNet
  975. {
  976. [app messageNotification:@"E2E delete public key" description:@"Public key was deleted" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  977. }
  978. - (void)deleteEndToEndPublicKeyFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  979. {
  980. [app messageNotification:@"E2E delete public key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  981. }
  982. // ++++++++++++++++++++++ PRIVATE KEY ++++++++++++++++++++++
  983. - (void)getEndToEndPrivateKeySuccess:(CCMetadataNet *)metadataNet
  984. {
  985. // Activity
  986. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:@"EndToEndPrivateKey present on Server" type:k_activityTypeSuccess verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  987. #ifdef DEBUG
  988. [app messageNotification:@"Get E2E PrivateKey" description:@"Success" visible:YES delay:1 type:TWMessageBarMessageTypeSuccess errorCode:0];
  989. #endif
  990. }
  991. - (void)getEndToEndPrivateKeyFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  992. {
  993. switch (errorCode) {
  994. case 400:
  995. message = @"bad request: unpredictable internal error";
  996. [app messageNotification:@"E2E private key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  997. break;
  998. case 404: {
  999. // remove keychain
  1000. [CCUtility setEndToEndPrivateKey:app.activeUser privateKey:nil];
  1001. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1002. NSString *mnemonic = [[NYMnemonic generateMnemonicString:@128 language:@"english"] stringByReplacingOccurrencesOfString:@" " withString:@""];
  1003. mnemonic = @"moreovertelevisionfactorytendencyindependenceinternationalintellectualimpressinterestvolunteer";
  1004. NSString *privateKeyEncoded = [[NCEndToEndEncryption sharedManager] createEndToEndPrivateKey:app.directoryUser mnemonic:mnemonic];
  1005. if (privateKeyEncoded) {
  1006. metadataNet.action = actionStoreEndToEndPrivateKey;
  1007. metadataNet.options = privateKeyEncoded;
  1008. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1009. } else {
  1010. // Activity
  1011. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:@"Error to create PrivateKeyEncoded" type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  1012. }
  1013. message = @"private key doesn't exists";
  1014. }
  1015. break;
  1016. case 409:
  1017. message = @"forbidden: the user can't access the private key";
  1018. [app messageNotification:@"E2E private key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1019. break;
  1020. default:
  1021. [app messageNotification:@"E2E private key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1022. break;
  1023. }
  1024. // Activity
  1025. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:message type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  1026. }
  1027. - (void)storeEndToEndPrivateKeySuccess:(CCMetadataNet *)metadataNet
  1028. {
  1029. // Store key locally keychain
  1030. [CCUtility setEndToEndPrivateKey:app.activeUser privateKey:metadataNet.options];
  1031. // Activity
  1032. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:@"EndToEndPrivateKey stored on Server and stored locally" type:k_activityTypeSuccess verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  1033. #ifdef DEBUG
  1034. [app messageNotification:@"Store E2E PrivateKey" description:@"Success" visible:YES delay:1 type:TWMessageBarMessageTypeSuccess errorCode:0];
  1035. #endif
  1036. }
  1037. - (void)storeEndToEndPrivateKeyFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1038. {
  1039. [app messageNotification:@"E2E sign private key" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1040. // Activity
  1041. [[NCManageDatabase sharedInstance] addActivityClient:@"" fileID:@"" action:k_activityDebugActionEndToEndEncryption selector:metadataNet.selector note:message type:k_activityTypeFailure verbose:k_activityVerboseHigh activeUrl:app.activeUrl];
  1042. }
  1043. - (void)deleteEndToEndPrivateKeySuccess:(CCMetadataNet *)metadataNet
  1044. {
  1045. [app messageNotification:@"E2E delete private key" description:@"Private key was deleted" visible:YES delay:1 type:TWMessageBarMessageTypeSuccess errorCode:0];
  1046. }
  1047. - (void)deleteEndToEndPrivateKeyFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1048. {
  1049. [app messageNotification:@"E2E delete private key" description:message visible:YES delay:1 type:TWMessageBarMessageTypeError errorCode:errorCode];
  1050. }
  1051. #pragma mark -
  1052. #pragma --------------------------------------------------------------------------------------------
  1053. #pragma mark ==== Download Thumbnail Delegate ====
  1054. #pragma --------------------------------------------------------------------------------------------
  1055. - (void)downloadThumbnailFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1056. {
  1057. NSLog(@"[LOG] Download Thumbnail Failure error %lu, %@", (long)errorCode, message);
  1058. }
  1059. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  1060. {
  1061. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  1062. if ([self indexPathIsValid:indexPath]) {
  1063. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]])
  1064. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  1065. }
  1066. }
  1067. #pragma --------------------------------------------------------------------------------------------
  1068. #pragma mark ==== Download ====
  1069. #pragma --------------------------------------------------------------------------------------------
  1070. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1071. {
  1072. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1073. // File do not exists on server, remove in local
  1074. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  1075. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID] error:nil];
  1076. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID] error:nil];
  1077. if (metadata.directory && serverUrl) {
  1078. NSString *dirForDelete = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1079. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:dirForDelete];
  1080. }
  1081. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID] clearDateReadDirectoryID:nil];
  1082. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1083. }
  1084. if ([selector isEqualToString:selectorLoadViewImage]) {
  1085. dispatch_async(dispatch_get_main_queue(), ^{
  1086. // Updating Detail
  1087. if (app.activeDetail)
  1088. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  1089. // Updating Photos
  1090. if (app.activePhotos)
  1091. [app.activePhotos downloadFileFailure:errorCode];
  1092. });
  1093. } else {
  1094. if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized)
  1095. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1096. }
  1097. [self reloadDatasource:serverUrl];
  1098. }
  1099. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1100. {
  1101. __block tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1102. if (metadata == nil)
  1103. return;
  1104. // Download
  1105. if ([selector isEqualToString:selectorDownloadFile]) {
  1106. [self reloadDatasource:serverUrl];
  1107. }
  1108. // Synchronized
  1109. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  1110. [self reloadDatasource:serverUrl];
  1111. }
  1112. // add Favorite
  1113. if ([selector isEqualToString:selectorAddFavorite]) {
  1114. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1115. }
  1116. // open View File
  1117. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1118. [self reloadDatasource:serverUrl];
  1119. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1120. selector = selectorOpenIn;
  1121. //[self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1122. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1123. selector = selectorOpenIn;
  1124. } else {
  1125. _metadata = metadata;
  1126. if ([self shouldPerformSegue])
  1127. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1128. }
  1129. }
  1130. // Open with...
  1131. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1132. [self reloadDatasource:serverUrl];
  1133. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  1134. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  1135. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName]];
  1136. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1137. _docController.delegate = self;
  1138. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1139. }
  1140. // Save to Photo Album
  1141. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1142. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1143. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1144. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1145. if (image)
  1146. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1147. else
  1148. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1149. }
  1150. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1151. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileName] error:nil];
  1152. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileName])) {
  1153. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileName], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1154. } else {
  1155. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1156. }
  1157. }
  1158. [self reloadDatasource:serverUrl];
  1159. }
  1160. // Copy File
  1161. if ([selector isEqualToString:selectorLoadCopy]) {
  1162. [self reloadDatasource:serverUrl];
  1163. [self copyFileToPasteboard:metadata];
  1164. }
  1165. //download file plist
  1166. if ([selector isEqualToString:selectorLoadPlist]) {
  1167. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1168. long countSelectorLoadPlist = 0;
  1169. for (NSOperation *operation in [app.netQueue operations]) {
  1170. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1171. countSelectorLoadPlist++;
  1172. }
  1173. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1174. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:directoryID] && directoryID) {
  1175. dispatch_async(dispatch_get_main_queue(), ^{
  1176. [self reloadDatasource:serverUrl];
  1177. });
  1178. }
  1179. });
  1180. }
  1181. //selectorLoadViewImage
  1182. if ([selector isEqualToString:selectorLoadViewImage]) {
  1183. // Detail
  1184. if (app.activeDetail)
  1185. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1186. // Photos
  1187. if (app.activePhotos)
  1188. [app.activePhotos downloadFileSuccess:metadata];
  1189. [self reloadDatasource:serverUrl];
  1190. }
  1191. // if exists postselector call self with selectorPost
  1192. if ([selectorPost length] > 0)
  1193. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1194. // Auto Download Upload
  1195. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1196. // ONLY BACKGROUND
  1197. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1198. } else {
  1199. // ONLY FOREFROUND
  1200. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1201. }
  1202. }
  1203. - (void)downloadSelectedFilesFolders
  1204. {
  1205. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1206. return;
  1207. NSLog(@"[LOG] Start download selected ...");
  1208. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1209. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1210. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1211. for (tableMetadata *metadata in selectedMetadatas) {
  1212. if (metadata.directory) {
  1213. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1214. if (serverUrl) {
  1215. serverUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  1216. [[CCSynchronize sharedSynchronize] readFolder:serverUrl selector:selectorReadFolderWithDownload];
  1217. }
  1218. } else {
  1219. [[CCSynchronize sharedSynchronize] readFile:metadata selector:selectorReadFileWithDownload];
  1220. }
  1221. }
  1222. [_hud hideHud];
  1223. });
  1224. [self tableViewSelect:NO];
  1225. }
  1226. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1227. {
  1228. }
  1229. #pragma --------------------------------------------------------------------------------------------
  1230. #pragma mark ===== Upload new Photos/Videos =====
  1231. #pragma --------------------------------------------------------------------------------------------
  1232. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1233. {
  1234. // Auto Download Upload
  1235. if([selector isEqualToString:selectorUploadAutoUpload] || [selector isEqualToString:selectorUploadAutoUploadAll] || [selector isEqualToString:selectorUploadFile]) {
  1236. if ([[NCManageDatabase sharedInstance] getPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier] > k_priorityAutoUploadStop) {
  1237. // Change priority Auto Upload
  1238. if ([[NCManageDatabase sharedInstance] setPriorityQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier priority:k_priorityAutoUploadError]) {
  1239. // Activity
  1240. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:message type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1241. }
  1242. if (errorCode != kCFURLErrorCancelled)
  1243. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1244. } else {
  1245. // Delete record on Table Auto Upload
  1246. [[NCManageDatabase sharedInstance] deleteQueueUploadWithAssetLocalIdentifier:metadataNet.assetLocalIdentifier selector:selector];
  1247. // Activity
  1248. [[NCManageDatabase sharedInstance] addActivityClient:metadataNet.fileName fileID:metadataNet.assetLocalIdentifier action:k_activityDebugActionUpload selector:selector note:@"Too many error, file deleted" type:k_activityTypeFailure verbose:k_activityVerboseDefault activeUrl:app.activeUrl];
  1249. [app messageNotification:@"_upload_file_" description:@"Too many error, file deleted, see Activity for more info" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1250. }
  1251. } else {
  1252. // Read File test do not exists
  1253. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1254. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  1255. // reUpload
  1256. if (metadata)
  1257. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1258. }
  1259. // Print error
  1260. else if (errorCode != kCFURLErrorCancelled && errorCode != kOCErrorServerUnauthorized) {
  1261. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1262. }
  1263. }
  1264. [self reloadDatasource:serverUrl];
  1265. }
  1266. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1267. {
  1268. // Auto Download Upload
  1269. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) {
  1270. // ONLY BACKGROUND
  1271. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUploadBackground] waitUntilDone:NO];
  1272. } else {
  1273. // ONLY FOREFROUND
  1274. [app performSelectorOnMainThread:@selector(loadAutoDownloadUpload:) withObject:[NSNumber numberWithInt:k_maxConcurrentOperationDownloadUpload] waitUntilDone:NO];
  1275. }
  1276. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1277. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1278. [self readFolder:serverUrl];
  1279. } else {
  1280. [self reloadDatasource:serverUrl];
  1281. }
  1282. });
  1283. }
  1284. //
  1285. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1286. //
  1287. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1288. {
  1289. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1290. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1291. });
  1292. }
  1293. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1294. {
  1295. NSArray *assets = [arguments objectAtIndex:0];
  1296. NSString *serverUrl = [arguments objectAtIndex:1];
  1297. BOOL useSubFolder = [[arguments objectAtIndex:2] boolValue];
  1298. NSString *session = [arguments objectAtIndex:3];
  1299. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  1300. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1301. if (!directoryID) return;
  1302. // if request create the folder for Photos & the subfolders
  1303. if ([autoUploadPath isEqualToString:serverUrl])
  1304. if (![[NCAutoUpload sharedInstance] createFolderSubFolderAutoUploadFolderPhotos:autoUploadPath useSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  1305. return;
  1306. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1307. for (PHAsset *asset in assets) {
  1308. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType];
  1309. NSDate *assetDate = asset.creationDate;
  1310. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1311. // Create serverUrl if use sub folder
  1312. if (useSubFolder) {
  1313. [formatter setDateFormat:@"yyyy"];
  1314. NSString *yearString = [formatter stringFromDate:assetDate];
  1315. [formatter setDateFormat:@"MM"];
  1316. NSString *monthString = [formatter stringFromDate:assetDate];
  1317. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  1318. }
  1319. // Check if is in upload
  1320. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@ AND session != ''", app.activeAccount, directoryID, fileName];
  1321. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1322. if ([isRecordInSessions count] > 0) {
  1323. // next upload
  1324. continue;
  1325. } else {
  1326. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1327. metadataNet.action = actionReadFile;
  1328. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1329. metadataNet.fileName = fileName;
  1330. metadataNet.session = session;
  1331. metadataNet.selector = selectorReadFileUploadFile;
  1332. metadataNet.serverUrl = serverUrl;
  1333. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1334. }
  1335. }
  1336. }
  1337. #pragma --------------------------------------------------------------------------------------------
  1338. #pragma mark ==== Read File ====
  1339. #pragma --------------------------------------------------------------------------------------------
  1340. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1341. {
  1342. // Unauthorized
  1343. if (errorCode == kOCErrorServerUnauthorized)
  1344. [app openLoginView:self loginType:loginModifyPasswordUser];
  1345. // UploadFile
  1346. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1347. // File not exists
  1348. if (errorCode == 404) {
  1349. metadataNet.errorCode = 0;
  1350. metadataNet.selector = selectorUploadFile;
  1351. metadataNet.selectorPost = nil;
  1352. metadataNet.taskStatus = k_taskStatusResume;
  1353. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1354. } else {
  1355. // error ho many retry befor notification and go to on next asses
  1356. if (metadataNet.errorRetry < 3) {
  1357. // Retry read file
  1358. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1359. } else {
  1360. // STOP check file, view message error
  1361. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1362. }
  1363. }
  1364. }
  1365. }
  1366. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1367. {
  1368. // Read Folder
  1369. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  1370. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", metadataNet.account, metadataNet.serverUrl]];
  1371. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  1372. [self readFolder:metadataNet.serverUrl];
  1373. }
  1374. }
  1375. // UploadFile
  1376. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1377. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1378. metadataNet.selector = selectorUploadFile;
  1379. metadataNet.selectorPost = nil;
  1380. metadataNet.taskStatus = k_taskStatusResume;
  1381. (void)[[NCManageDatabase sharedInstance] addQueueUploadWithMetadataNet:metadataNet];
  1382. }
  1383. }
  1384. - (void)readFileReloadFolder
  1385. {
  1386. if (!_serverUrl || !app.activeAccount || app.maintenanceMode)
  1387. return;
  1388. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1389. metadataNet.action = actionReadFile;
  1390. metadataNet.priority = NSOperationQueuePriorityHigh;
  1391. metadataNet.selector = selectorReadFileReloadFolder;
  1392. metadataNet.serverUrl = _serverUrl;
  1393. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1394. }
  1395. #pragma --------------------------------------------------------------------------------------------
  1396. #pragma mark ==== Read Folder ====
  1397. #pragma --------------------------------------------------------------------------------------------
  1398. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1399. {
  1400. // stoprefresh
  1401. [_refreshControl endRefreshing];
  1402. // Unauthorized
  1403. if (errorCode == kOCErrorServerUnauthorized)
  1404. [app openLoginView:self loginType:loginModifyPasswordUser];
  1405. _loadingFolder = NO;
  1406. [self tableViewReloadData];
  1407. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1408. // verify active user
  1409. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1410. if (message && [record.account isEqualToString:metadataNet.account])
  1411. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1412. [self reloadDatasource:metadataNet.serverUrl];
  1413. }
  1414. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas
  1415. {
  1416. // stoprefresh
  1417. [_refreshControl endRefreshing];
  1418. // verify active user
  1419. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1420. if (![record.account isEqualToString:metadataNet.account])
  1421. return;
  1422. // save father e update permission
  1423. if(!_isSearchMode && metadataFolder)
  1424. _fatherPermission = metadataFolder.permissions;
  1425. NSArray *recordsInSessions;
  1426. NSMutableArray *metadatasToInsertInDB = [NSMutableArray new];
  1427. if (_isSearchMode) {
  1428. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", metadataNet.account] sorted:nil ascending:NO];
  1429. } else {
  1430. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag];
  1431. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", metadataNet.account, metadataNet.directoryID] clearDateReadDirectoryID:metadataNet.directoryID];
  1432. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session != ''", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1433. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1434. }
  1435. for (tableMetadata *metadata in metadatas) {
  1436. // verify if the record is in download/upload progress
  1437. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1438. tableMetadata *metadataTransfer = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND fileName = %@", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1439. // is in Download or Upload
  1440. if ([metadataTransfer.session containsString:@"upload"] || [metadataTransfer.session containsString:@"download"]) {
  1441. continue;
  1442. }
  1443. }
  1444. // Insert in Array
  1445. [metadatasToInsertInDB addObject:metadata];
  1446. }
  1447. // insert in Database
  1448. metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl];
  1449. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1450. // read plist
  1451. if (!_isSearchMode)
  1452. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1453. // File is changed ??
  1454. if (!_isSearchMode && metadatasToInsertInDB)
  1455. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1456. });
  1457. // Search Mode
  1458. if (_isSearchMode) {
  1459. // Fix managed -> Unmanaged _searchResultMetadatas
  1460. if (metadatasToInsertInDB)
  1461. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1462. [self reloadDatasource:metadataNet.serverUrl];
  1463. }
  1464. // this is the same directory
  1465. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1466. // reload
  1467. [self reloadDatasource:metadataNet.serverUrl];
  1468. // Enable change user
  1469. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1470. _loadingFolder = NO;
  1471. [self tableViewReloadData];
  1472. }
  1473. }
  1474. - (void)readFolder:(NSString *)serverUrl
  1475. {
  1476. // init control
  1477. if (!serverUrl || !app.activeAccount || app.maintenanceMode) {
  1478. [_refreshControl endRefreshing];
  1479. return;
  1480. }
  1481. // Search Mode
  1482. if (_isSearchMode) {
  1483. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1484. _searchFileName = @""; // forced reload searchg
  1485. [self updateSearchResultsForSearchController:self.searchController];
  1486. return;
  1487. }
  1488. _loadingFolder = YES;
  1489. [self tableViewReloadData];
  1490. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  1491. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1492. metadataNet.action = actionReadFolder;
  1493. metadataNet.date = [NSDate date];
  1494. metadataNet.depth = @"1";
  1495. metadataNet.directoryID = directory.directoryID;
  1496. metadataNet.priority = NSOperationQueuePriorityHigh;
  1497. metadataNet.selector = selectorReadFolder;
  1498. metadataNet.serverUrl = serverUrl;
  1499. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1500. }
  1501. #pragma mark -
  1502. #pragma --------------------------------------------------------------------------------------------
  1503. #pragma mark ===== Search =====
  1504. #pragma --------------------------------------------------------------------------------------------
  1505. -(void)searchStartTimer
  1506. {
  1507. NSString *home = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  1508. [[CCActions sharedInstance] search:home fileName:_searchFileName depth:@"infinity" date:nil selector:selectorSearch delegate:self];
  1509. _noFilesSearchTitle = @"";
  1510. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1511. [self.tableView reloadEmptyDataSet];
  1512. }
  1513. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1514. {
  1515. //[self setNeedsStatusBarAppearanceUpdate];
  1516. _isSearchMode = YES;
  1517. [self deleteRefreshControl];
  1518. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1519. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1520. _searchFileName = fileName;
  1521. // First : filter
  1522. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1523. if (!directoryID) return;
  1524. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID = %@ AND account = %@ AND fileName CONTAINS[cd] %@", directoryID, app.activeAccount, fileName];
  1525. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1526. [_searchResultMetadatas removeAllObjects];
  1527. for (tableMetadata *record in records)
  1528. [_searchResultMetadatas addObject:record];
  1529. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1530. metadataNet.account = app.activeAccount;
  1531. metadataNet.directoryID = directoryID;
  1532. metadataNet.selector = selectorSearch;
  1533. metadataNet.serverUrl = _serverUrl;
  1534. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas];
  1535. // Version >= 12
  1536. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1537. [_timerWaitInput invalidate];
  1538. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1539. }
  1540. }
  1541. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1542. [self reloadDatasource];
  1543. }
  1544. }
  1545. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1546. {
  1547. [self cancelSearchBar];
  1548. [self readFolder:_serverUrl];
  1549. }
  1550. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1551. {
  1552. // Unauthorized
  1553. if (errorCode == kOCErrorServerUnauthorized)
  1554. [app openLoginView:self loginType:loginModifyPasswordUser];
  1555. if (message && errorCode != kOCErrorServerUnauthorized)
  1556. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1557. _searchFileName = @"";
  1558. }
  1559. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1560. {
  1561. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1562. [self readFolderSuccess:metadataNet metadataFolder:nil metadatas:metadatas];
  1563. }
  1564. - (void)cancelSearchBar
  1565. {
  1566. if (self.searchController.active) {
  1567. [self.searchController setActive:NO];
  1568. [self createRefreshControl];
  1569. _isSearchMode = NO;
  1570. _searchFileName = @"";
  1571. _dateReadDataSource = nil;
  1572. _searchResultMetadatas = [NSMutableArray new];
  1573. [self reloadDatasource];
  1574. }
  1575. //[self setNeedsStatusBarAppearanceUpdate];
  1576. }
  1577. #pragma mark -
  1578. #pragma --------------------------------------------------------------------------------------------
  1579. #pragma mark ===== Delete File or Folder =====
  1580. #pragma --------------------------------------------------------------------------------------------
  1581. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1582. {
  1583. // Unauthorized
  1584. if (errorCode == kOCErrorServerUnauthorized)
  1585. [app openLoginView:self loginType:loginModifyPasswordUser];
  1586. NSLog(@"[LOG] Delete File failure error %lu, %@", (long)errorCode, message);
  1587. [self deleteFileOrFolderSuccess:metadataNet];
  1588. }
  1589. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1590. {
  1591. [_queueSelector removeObject:metadataNet.selector];
  1592. if ([_queueSelector count] == 0) {
  1593. [_hud hideHud];
  1594. // next
  1595. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1596. if ([_selectedFileIDsMetadatas count] > 0) {
  1597. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1598. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1599. } else {
  1600. // End Select Table View
  1601. [self tableViewSelect:NO];
  1602. // Reload
  1603. if (_isSearchMode)
  1604. [self readFolder:metadataNet.serverUrl];
  1605. else
  1606. [self reloadDatasource:metadataNet.serverUrl];
  1607. }
  1608. }
  1609. }
  1610. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1611. {
  1612. [_queueSelector addObject:selectorDelete];
  1613. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1614. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1615. }
  1616. - (void)deleteFile
  1617. {
  1618. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1619. return;
  1620. [_queueSelector removeAllObjects];
  1621. if ([_selectedFileIDsMetadatas count] > 0) {
  1622. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1623. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1624. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1625. } else {
  1626. _numSelectedFileIDsMetadatas = 1;
  1627. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1628. }
  1629. }
  1630. #pragma --------------------------------------------------------------------------------------------
  1631. #pragma mark ===== Rename / Move =====
  1632. #pragma --------------------------------------------------------------------------------------------
  1633. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1634. {
  1635. [self readFolder:metadataNet.serverUrl];
  1636. }
  1637. - (void)renameFile:(NSArray *)arguments
  1638. {
  1639. tableMetadata* metadata = [arguments objectAtIndex:0];
  1640. NSString *fileName = [arguments objectAtIndex:1];
  1641. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1642. }
  1643. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1644. {
  1645. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1646. [_hud hideHud];
  1647. if (message && errorCode != kOCErrorServerUnauthorized)
  1648. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1649. // End Select Table View
  1650. [self tableViewSelect:NO];
  1651. // reload Datasource
  1652. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1653. [self readFolder:metadataNet.serverUrl];
  1654. else
  1655. [self reloadDatasource];
  1656. }
  1657. }
  1658. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1659. {
  1660. [_queueSelector removeObject:metadataNet.selector];
  1661. if ([_queueSelector count] == 0) {
  1662. [_hud hideHud];
  1663. NSString *fileName = metadataNet.fileName;
  1664. NSString *directoryID = metadataNet.directoryID;
  1665. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1666. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1667. if (!serverUrlTo) return;
  1668. // FILE -> Metadata
  1669. if (metadataNet.directory == NO)
  1670. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1671. // DIRECTORY -> Directory - CCMetadata
  1672. if (metadataNet.directory == YES) {
  1673. // delete all dir / subdir
  1674. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1675. // move metadata
  1676. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1677. // Add new directory
  1678. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1679. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil];
  1680. }
  1681. // next
  1682. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1683. if ([_selectedFileIDsMetadatas count] > 0) {
  1684. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1685. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1686. } else {
  1687. // End Select Table View
  1688. [self tableViewSelect:NO];
  1689. // reload Datasource
  1690. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1691. [self readFolder:metadataNet.serverUrl];
  1692. else
  1693. [self reloadDatasource];
  1694. }
  1695. }
  1696. }
  1697. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1698. {
  1699. tableMetadata *metadata = [arguments objectAtIndex:0];
  1700. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1701. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1702. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1703. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1704. if (!serverUrl) return;
  1705. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1706. if (!directoryIDTo) return;
  1707. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withUserID:app.activeUserID withPassword:app.activePassword withUrl:app.activeUrl];
  1708. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1709. if(!error) {
  1710. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1711. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1712. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1713. }];
  1714. [alert addAction:ok];
  1715. [self presentViewController:alert animated:YES completion:nil];
  1716. });
  1717. // End Select Table View
  1718. [self tableViewSelect:NO];
  1719. // reload Datasource
  1720. [self readFileReloadFolder];
  1721. return;
  1722. }
  1723. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1724. metadataNet.action = actionMoveFileOrFolder;
  1725. metadataNet.directory = metadata.directory;
  1726. metadataNet.fileID = metadata.fileID;
  1727. metadataNet.directoryID = metadata.directoryID;
  1728. metadataNet.directoryIDTo = directoryIDTo;
  1729. metadataNet.fileName = metadata.fileName;
  1730. metadataNet.fileNameTo = metadata.fileName;
  1731. metadataNet.etag = metadata.etag;
  1732. metadataNet.selector = selectorMove;
  1733. metadataNet.serverUrl = serverUrl;
  1734. metadataNet.serverUrlTo = serverUrlTo;
  1735. [_queueSelector addObject:metadataNet.selector];
  1736. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1737. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1738. }
  1739. // DELEGATE : Move
  1740. - (void)dismissMove
  1741. {
  1742. [self reloadDatasource];
  1743. }
  1744. // DELEGATE : Move
  1745. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1746. {
  1747. [_queueSelector removeAllObjects];
  1748. if ([_selectedFileIDsMetadatas count] > 0) {
  1749. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1750. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1751. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1752. } else {
  1753. _numSelectedFileIDsMetadatas = 1;
  1754. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1755. }
  1756. }
  1757. - (void)moveOpenWindow:(NSArray *)indexPaths
  1758. {
  1759. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1760. return;
  1761. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1762. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1763. viewController.delegate = self;
  1764. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1765. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1766. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1767. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1768. viewController.networkingOperationQueue = app.netQueue;
  1769. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1770. [self presentViewController:navigationController animated:YES completion:nil];
  1771. }
  1772. #pragma --------------------------------------------------------------------------------------------
  1773. #pragma mark ===== Create folder =====
  1774. #pragma --------------------------------------------------------------------------------------------
  1775. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1776. {
  1777. // Unauthorized
  1778. if (errorCode == kOCErrorServerUnauthorized)
  1779. [app openLoginView:self loginType:loginModifyPasswordUser];
  1780. if (message && errorCode != kOCErrorServerUnauthorized)
  1781. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1782. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1783. [self reloadDatasource];
  1784. // We are in directory fail ?
  1785. CCMain *vc = [app.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1786. if (vc)
  1787. [vc.navigationController popViewControllerAnimated:YES];
  1788. }
  1789. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1790. {
  1791. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1792. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil];
  1793. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID]];
  1794. if (metadata) {
  1795. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID] clearDateReadDirectoryID:nil];
  1796. metadata.fileID = metadataNet.fileID;
  1797. metadata.date = metadataNet.date;
  1798. metadata.permissions = @"RDNVCK";
  1799. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1800. [self reloadDatasource];
  1801. } else {
  1802. [self readFileReloadFolder];
  1803. }
  1804. }
  1805. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1806. {
  1807. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1808. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1809. if (![fileNameFolder length]) return;
  1810. //if (autoUploadDirectory) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  1811. //else metadataNet.serverUrl = _serverUrl;
  1812. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1813. if (!directoryID) return;
  1814. metadataNet.action = actionCreateFolder;
  1815. metadataNet.directoryID = directoryID;
  1816. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1817. metadataNet.fileName = fileNameFolder;
  1818. metadataNet.selector = selectorCreateFolder;
  1819. metadataNet.serverUrl = serverUrl;
  1820. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1821. // Create Directory on metadata
  1822. tableMetadata *metadata = [CCUtility createMetadataWithAccount:app.activeAccount date:[NSDate date] directory:YES fileID:metadataNet.fileID directoryID:metadataNet.directoryID fileName:metadataNet.fileName etag:@"" size:0 status:k_metadataStatusNormal];
  1823. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1824. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1825. [self reloadDatasource];
  1826. }
  1827. #pragma --------------------------------------------------------------------------------------------
  1828. #pragma mark ===== Encrypted / Decrypted Folder =====
  1829. #pragma --------------------------------------------------------------------------------------------
  1830. - (void)encyptedDecryptedFolder
  1831. {
  1832. }
  1833. #pragma --------------------------------------------------------------------------------------------
  1834. #pragma mark ===== Encrypted/Decrypted File =====
  1835. #pragma --------------------------------------------------------------------------------------------
  1836. - (void)encryptedSelectedFiles
  1837. {
  1838. }
  1839. - (void)decryptedSelectedFiles
  1840. {
  1841. }
  1842. - (void)cmdEncryptedDecryptedFile
  1843. {
  1844. }
  1845. - (void)encryptedFile:(tableMetadata *)metadata
  1846. {
  1847. }
  1848. - (void)decryptedFile:(tableMetadata *)metadata
  1849. {
  1850. }
  1851. #pragma --------------------------------------------------------------------------------------------
  1852. #pragma mark ===== Progress & Task Button =====
  1853. #pragma --------------------------------------------------------------------------------------------
  1854. - (void)triggerProgressTask:(NSNotification *)notification
  1855. {
  1856. NSDictionary *dict = notification.userInfo;
  1857. NSString *fileID = [dict valueForKey:@"fileID"];
  1858. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1859. float progress = [[dict valueForKey:@"progress"] floatValue];
  1860. // Check
  1861. if (!fileID || [fileID isEqualToString: @""])
  1862. return;
  1863. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1864. if (![serverUrl isEqualToString:_serverUrl])
  1865. return;
  1866. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1867. if ([self indexPathIsValid:indexPath]) {
  1868. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1869. cell.progressView.progressTintColor = [UIColor blackColor];
  1870. cell.progressView.hidden = NO;
  1871. [cell.progressView setProgress:progress];
  1872. }
  1873. }
  1874. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1875. {
  1876. UITouch * touch = [[event allTouches] anyObject];
  1877. CGPoint location = [touch locationInView:self.tableView];
  1878. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1879. if ([self indexPathIsValid:indexPath]) {
  1880. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1881. if (metadata)
  1882. [self reloadTaskButton:metadata];
  1883. }
  1884. }
  1885. - (void)reloadTaskButton:(tableMetadata *)metadata
  1886. {
  1887. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1888. __block NSURLSessionTask *findTask;
  1889. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1890. NSString *fileID = metadata.fileID;
  1891. // DOWNLOAD
  1892. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1893. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1894. for (NSURLSessionUploadTask *task in downloadTasks)
  1895. if (task.taskIdentifier == sessionTaskIdentifier) {
  1896. findTask = task;
  1897. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1898. [task cancel];
  1899. }
  1900. if (!findTask) {
  1901. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1902. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1903. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1904. }
  1905. }];
  1906. }
  1907. // UPLOAD
  1908. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1909. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1910. for (NSURLSessionUploadTask *task in uploadTasks)
  1911. if (task.taskIdentifier == sessionTaskIdentifier) {
  1912. findTask = task;
  1913. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1914. [task cancel];
  1915. }
  1916. if (!findTask) {
  1917. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1918. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1919. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1920. }
  1921. }];
  1922. }
  1923. }
  1924. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1925. {
  1926. UITouch * touch = [[event allTouches] anyObject];
  1927. CGPoint location = [touch locationInView:self.tableView];
  1928. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1929. if ([self indexPathIsValid:indexPath]) {
  1930. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1931. if (metadata)
  1932. [self cancelTaskButton:metadata reloadTable:YES];
  1933. }
  1934. }
  1935. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  1936. {
  1937. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1938. __block NSURLSessionTask *findTask;
  1939. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1940. NSString *fileID = metadata.fileID;
  1941. // DOWNLOAD
  1942. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1943. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1944. for (NSURLSessionTask *task in downloadTasks)
  1945. if (task.taskIdentifier == sessionTaskIdentifier) {
  1946. findTask = task;
  1947. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1948. [task cancel];
  1949. }
  1950. if (!findTask) {
  1951. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1952. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1953. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1954. }
  1955. }];
  1956. }
  1957. // UPLOAD
  1958. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1959. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1960. for (NSURLSessionUploadTask *task in uploadTasks)
  1961. if (task.taskIdentifier == sessionTaskIdentifier) {
  1962. findTask = task;
  1963. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1964. [task cancel];
  1965. }
  1966. if (!findTask) {
  1967. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1968. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1969. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1970. }
  1971. }];
  1972. }
  1973. }
  1974. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1975. {
  1976. UITouch * touch = [[event allTouches] anyObject];
  1977. CGPoint location = [touch locationInView:self.tableView];
  1978. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1979. if ([self indexPathIsValid:indexPath]) {
  1980. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1981. if (metadata)
  1982. [self stopTaskButton:metadata];
  1983. }
  1984. }
  1985. - (void)stopTaskButton:(tableMetadata *)metadata
  1986. {
  1987. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1988. __block NSURLSessionTask *findTask;
  1989. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1990. NSString *fileID = metadata.fileID;
  1991. // UPLOAD
  1992. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1993. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1994. for (NSURLSessionUploadTask *task in uploadTasks)
  1995. if (task.taskIdentifier == sessionTaskIdentifier) {
  1996. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1997. findTask = task;
  1998. [task cancel];
  1999. }
  2000. if (!findTask) {
  2001. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2002. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  2003. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  2004. }
  2005. }];
  2006. }
  2007. }
  2008. #pragma --------------------------------------------------------------------------------------------
  2009. #pragma mark ===== Shared =====
  2010. #pragma --------------------------------------------------------------------------------------------
  2011. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2012. {
  2013. [_hud hideHud];
  2014. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2015. // change account ?
  2016. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2017. if([record.account isEqualToString:metadataNet.account] == NO)
  2018. return;
  2019. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  2020. if (result) {
  2021. appDelegate.sharesLink = result[0];
  2022. appDelegate.sharesUserAndGroup = result[1];
  2023. }
  2024. // Notify Shares View
  2025. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  2026. if (openWindow) {
  2027. if (_shareOC) {
  2028. [_shareOC reloadData];
  2029. } else {
  2030. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2031. // Apriamo la view
  2032. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2033. _shareOC.delegate = self;
  2034. _shareOC.metadata = metadata;
  2035. _shareOC.serverUrl = metadataNet.serverUrl;
  2036. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2037. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2038. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2039. [self presentViewController:_shareOC animated:YES completion:nil];
  2040. }
  2041. }
  2042. [self tableViewReloadData];
  2043. }
  2044. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2045. {
  2046. [_hud hideHud];
  2047. // Unauthorized
  2048. if (errorCode == kOCErrorServerUnauthorized)
  2049. [app openLoginView:self loginType:loginModifyPasswordUser];
  2050. if (errorCode != kOCErrorServerUnauthorized)
  2051. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2052. if (_shareOC)
  2053. [_shareOC reloadData];
  2054. [self tableViewReloadData];
  2055. }
  2056. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2057. {
  2058. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2059. metadataNet.action = actionShare;
  2060. metadataNet.fileID = metadata.fileID;
  2061. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2062. metadataNet.password = password;
  2063. metadataNet.selector = selectorShare;
  2064. metadataNet.serverUrl = serverUrl;
  2065. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2066. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2067. }
  2068. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2069. {
  2070. [_hud hideHud];
  2071. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2072. // rimuoviamo la condivisione da db
  2073. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2074. if (result) {
  2075. appDelegate.sharesLink = result[0];
  2076. appDelegate.sharesUserAndGroup = result[1];
  2077. }
  2078. if (_shareOC)
  2079. [_shareOC reloadData];
  2080. [self tableViewReloadData];
  2081. }
  2082. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2083. {
  2084. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2085. metadataNet.action = actionUnShare;
  2086. metadataNet.fileID = metadata.fileID;
  2087. metadataNet.fileName = metadata.fileName;
  2088. metadataNet.selector = selectorUnshare;
  2089. metadataNet.serverUrl = serverUrl;
  2090. metadataNet.share = share;
  2091. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2092. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2093. }
  2094. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2095. {
  2096. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2097. metadataNet.action = actionUpdateShare;
  2098. metadataNet.fileID = metadata.fileID;
  2099. metadataNet.expirationTime = expirationTime;
  2100. metadataNet.password = password;
  2101. metadataNet.selector = selectorUpdateShare;
  2102. metadataNet.serverUrl = serverUrl;
  2103. metadataNet.share = share;
  2104. metadataNet.sharePermission = permission;
  2105. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2106. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2107. }
  2108. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2109. {
  2110. [_hud hideHud];
  2111. if (_shareOC)
  2112. [_shareOC reloadUserAndGroup:items];
  2113. }
  2114. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2115. {
  2116. [_hud hideHud];
  2117. // Unauthorized
  2118. if (errorCode == kOCErrorServerUnauthorized)
  2119. [app openLoginView:self loginType:loginModifyPasswordUser];
  2120. if (errorCode != kOCErrorServerUnauthorized)
  2121. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2122. }
  2123. - (void)getUserAndGroup:(NSString *)find
  2124. {
  2125. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2126. metadataNet.action = actionGetUserAndGroup;
  2127. metadataNet.options = find;
  2128. metadataNet.selector = selectorGetUserAndGroup;
  2129. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2130. [_hud visibleIndeterminateHud];
  2131. }
  2132. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2133. {
  2134. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2135. metadataNet.action = actionShareWith;
  2136. metadataNet.fileID = metadata.fileID;
  2137. metadataNet.directoryID = directoryID;
  2138. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2139. metadataNet.serverUrl = serverUrl;
  2140. metadataNet.selector = selectorShare;
  2141. metadataNet.share = user;
  2142. metadataNet.shareeType = shareeType;
  2143. metadataNet.sharePermission = permission;
  2144. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2145. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2146. }
  2147. - (void)openWindowShare:(tableMetadata *)metadata
  2148. {
  2149. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2150. if (!serverUrl) return;
  2151. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2152. metadataNet.action = actionReadShareServer;
  2153. metadataNet.fileID = metadata.fileID;
  2154. metadataNet.fileName = metadata.fileName;
  2155. metadataNet.selector = selectorOpenWindowShare;
  2156. metadataNet.serverUrl = serverUrl;
  2157. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2158. [_hud visibleIndeterminateHud];
  2159. }
  2160. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2161. {
  2162. CGPoint location = [tapGesture locationInView:self.tableView];
  2163. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2164. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2165. if (metadata)
  2166. [self openWindowShare:metadata];
  2167. }
  2168. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2169. {
  2170. CGPoint location = [tapGesture locationInView:self.tableView];
  2171. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2172. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2173. if (metadata) {
  2174. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2175. vc.metadata = metadata;
  2176. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2177. [self presentViewController:vc animated:YES completion:nil];
  2178. }
  2179. }
  2180. #pragma --------------------------------------------------------------------------------------------
  2181. #pragma mark ===== Favorite =====
  2182. #pragma --------------------------------------------------------------------------------------------
  2183. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2184. {
  2185. _dateReadDataSource = nil;
  2186. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2187. if (_isSearchMode)
  2188. [self readFolder:metadataNet.serverUrl];
  2189. else
  2190. [self reloadDatasource:metadataNet.serverUrl];
  2191. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2192. if (metadata.directory && metadata.favorite) {
  2193. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileName];
  2194. [app.activeFavorites addFavoriteFolder:dir];
  2195. }
  2196. }
  2197. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2198. {
  2199. // Unauthorized
  2200. if (errorCode == kOCErrorServerUnauthorized)
  2201. [app openLoginView:self loginType:loginModifyPasswordUser];
  2202. NSLog(@"[LOG] Setting Favorite failure error %lu, %@", (long)errorCode, message);
  2203. }
  2204. - (void)addFavorite:(tableMetadata *)metadata
  2205. {
  2206. if (metadata.directory) {
  2207. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2208. } else {
  2209. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2210. if (serverUrl)
  2211. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2212. }
  2213. }
  2214. - (void)removeFavorite:(tableMetadata *)metadata
  2215. {
  2216. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2217. }
  2218. #pragma --------------------------------------------------------------------------------------------
  2219. #pragma mark ===== Open in... =====
  2220. #pragma --------------------------------------------------------------------------------------------
  2221. - (void)openIn:(tableMetadata *)metadata
  2222. {
  2223. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2224. if (!serverUrl) return;
  2225. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2226. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2227. if ([self indexPathIsValid:indexPath])
  2228. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2229. }
  2230. #pragma --------------------------------------------------------------------------------------------
  2231. #pragma mark ===== Remove Local File =====
  2232. #pragma --------------------------------------------------------------------------------------------
  2233. - (void)removeLocalFile:(tableMetadata *)metadata
  2234. {
  2235. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2236. if (!serverUrl) return;
  2237. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2238. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2239. [self reloadDatasource:serverUrl];
  2240. }
  2241. #pragma --------------------------------------------------------------------------------------------
  2242. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2243. #pragma --------------------------------------------------------------------------------------------
  2244. - (void)orderTable:(NSString *)order
  2245. {
  2246. [CCUtility setOrderSettings:order];
  2247. // Clear data-read of DataSource
  2248. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2249. }
  2250. - (void)ascendingTable:(BOOL)ascending
  2251. {
  2252. [CCUtility setAscendingSettings:ascending];
  2253. // Clear data-read of DataSource
  2254. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2255. }
  2256. - (void)directoryOnTop:(BOOL)directoryOnTop
  2257. {
  2258. [CCUtility setDirectoryOnTop:directoryOnTop];
  2259. // Clear data-read of DataSource
  2260. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2261. }
  2262. - (void)tableGroupBy:(NSString *)groupBy
  2263. {
  2264. [CCUtility setGroupBySettings:groupBy];
  2265. // Clear data-read of DataSource
  2266. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2267. }
  2268. #pragma --------------------------------------------------------------------------------------------
  2269. #pragma mark ==== Menu LOGO ====
  2270. #pragma --------------------------------------------------------------------------------------------
  2271. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  2272. {
  2273. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2274. return;
  2275. // Brand
  2276. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2277. return;
  2278. NSUInteger numInSession = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", app.activeAccount] sorted:nil ascending:NO] count];
  2279. NSUInteger numInQueue = [app.netQueue operationCount];
  2280. if (numInSession+numInQueue > 0) {
  2281. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2282. return;
  2283. }
  2284. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2285. NSMutableArray *menuArray = [NSMutableArray new];
  2286. for (NSString *account in listAccount) {
  2287. if ([account isEqualToString:app.activeAccount]) continue;
  2288. CCMenuItem *item = [[CCMenuItem alloc] init];
  2289. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2290. item.argument = account;
  2291. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2292. item.target = self;
  2293. item.action = @selector(changeDefaultAccount:);
  2294. [menuArray addObject:item];
  2295. }
  2296. if ([menuArray count] == 0)
  2297. return;
  2298. OptionalConfiguration options;
  2299. Color textColor, backgroundColor;
  2300. textColor.R = 0;
  2301. textColor.G = 0;
  2302. textColor.B = 0;
  2303. backgroundColor.R = 1;
  2304. backgroundColor.G = 1;
  2305. backgroundColor.B = 1;
  2306. options.arrowSize = 9;
  2307. options.marginXSpacing = 7;
  2308. options.marginYSpacing = 10;
  2309. options.intervalSpacing = 20;
  2310. options.menuCornerRadius = 6.5;
  2311. options.maskToBackground = NO;
  2312. options.shadowOfMenu = YES;
  2313. options.hasSeperatorLine = YES;
  2314. options.seperatorLineHasInsets = YES;
  2315. options.textColor = textColor;
  2316. options.menuBackgroundColor = backgroundColor;
  2317. CGRect rect = self.view.frame;
  2318. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2319. CGFloat safeAreaTop = 0;
  2320. CGFloat offsetY = 35;
  2321. if (@available(iOS 11, *)) {
  2322. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2323. }
  2324. rect.origin.y = locationY + safeAreaTop + offsetY;
  2325. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2326. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2327. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2328. }
  2329. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2330. {
  2331. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2332. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2333. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2334. if (tableAccount)
  2335. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2336. // go to home sweet home
  2337. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2338. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2339. });
  2340. }
  2341. #pragma --------------------------------------------------------------------------------------------
  2342. #pragma mark ==== ReMenu ====
  2343. #pragma --------------------------------------------------------------------------------------------
  2344. - (void)createReMenuBackgroundView:(REMenu *)menu
  2345. {
  2346. CGFloat safeAreaBottom = 0;
  2347. CGFloat safeAreaTop = 0;
  2348. CGFloat statusBar = 0;
  2349. if (@available(iOS 11, *)) {
  2350. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  2351. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  2352. }
  2353. if ([UIApplication sharedApplication].isStatusBarHidden) {
  2354. statusBar = 13;
  2355. }
  2356. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2357. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2358. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  2359. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  2360. [UIView animateWithDuration:0.2 animations:^{
  2361. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  2362. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  2363. if (y>minimum) {
  2364. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  2365. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2366. }
  2367. }];
  2368. }
  2369. - (void)createReMainMenu
  2370. {
  2371. NSString *ordinamento;
  2372. NSString *groupBy = _directoryGroupBy;
  2373. __block NSString *nuovoOrdinamento;
  2374. NSString *titoloNuovo, *titoloAttuale;
  2375. BOOL ascendente;
  2376. __block BOOL nuovoAscendente;
  2377. UIImage *image;
  2378. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2379. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2380. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2381. [self tableViewSelect:YES];
  2382. }
  2383. }];
  2384. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2385. ordinamento = _directoryOrder;
  2386. if ([ordinamento isEqualToString:@"fileName"]) {
  2387. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2388. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2389. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2390. nuovoOrdinamento = @"date";
  2391. }
  2392. if ([ordinamento isEqualToString:@"date"]) {
  2393. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2394. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2395. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2396. nuovoOrdinamento = @"fileName";
  2397. }
  2398. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2399. [self orderTable:nuovoOrdinamento];
  2400. }];
  2401. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2402. ascendente = [CCUtility getAscendingSettings];
  2403. if (ascendente) {
  2404. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2405. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2406. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2407. nuovoAscendente = false;
  2408. }
  2409. if (!ascendente) {
  2410. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2411. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2412. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2413. nuovoAscendente = true;
  2414. }
  2415. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2416. [self ascendingTable:nuovoAscendente];
  2417. }];
  2418. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2419. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2420. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2421. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2422. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2423. else [self tableGroupBy:@"alphabetic"];
  2424. }];
  2425. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2426. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2427. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2428. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2429. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2430. else [self tableGroupBy:@"typefile"];
  2431. }];
  2432. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2433. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2434. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2435. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2436. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2437. else [self tableGroupBy:@"date"];
  2438. }];
  2439. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2440. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2441. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2442. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2443. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2444. else [self directoryOnTop:YES];
  2445. }];
  2446. // REMENU --------------------------------------------------------------------------------------------------------------
  2447. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2448. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2449. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2450. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2451. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2452. app.reMainMenu.separatorHeight = 0.5;
  2453. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2454. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2455. app.reMainMenu.textColor = [UIColor blackColor];
  2456. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2457. app.reMainMenu.textShadowColor = nil;
  2458. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2459. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2460. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2461. app.reMainMenu.highlightedSeparatorColor = nil;
  2462. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2463. app.reMainMenu.highlightedTextShadowColor = nil;
  2464. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2465. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2466. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2467. app.reMainMenu.subtitleTextShadowColor = nil;
  2468. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2469. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2470. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2471. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2472. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2473. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2474. app.reMainMenu.borderWidth = 0.3;
  2475. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2476. app.reMainMenu.animationDuration = 0.2;
  2477. app.reMainMenu.closeAnimationDuration = 0.2;
  2478. app.reMainMenu.bounce = NO;
  2479. [app.reMainMenu setClosePreparationBlock:^{
  2480. // Backgroun reMenu (Gesture)
  2481. [_reMenuBackgroundView removeFromSuperview];
  2482. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2483. }];
  2484. }
  2485. - (void)toggleReMainMenu
  2486. {
  2487. if (app.reMainMenu.isOpen) {
  2488. [app.reMainMenu close];
  2489. } else {
  2490. [self createReMainMenu];
  2491. [app.reMainMenu showFromNavigationController:self.navigationController];
  2492. // Backgroun reMenu & (Gesture)
  2493. [self createReMenuBackgroundView:app.reMainMenu];
  2494. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2495. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2496. }
  2497. }
  2498. - (void)createReSelectMenu
  2499. {
  2500. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2501. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2502. [self deleteFile];
  2503. }];
  2504. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2505. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2506. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2507. }];
  2508. /*
  2509. if (app.isCryptoCloudMode) {
  2510. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2511. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2512. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2513. }];
  2514. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2515. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2516. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2517. }];
  2518. }
  2519. */
  2520. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2521. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2522. [self downloadSelectedFilesFolders];
  2523. }];
  2524. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2525. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2526. [self saveSelectedFiles];
  2527. }];
  2528. // REMENU --------------------------------------------------------------------------------------------------------------
  2529. /*
  2530. if (app.isCryptoCloudMode) {
  2531. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2532. } else {
  2533. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2534. }
  2535. */
  2536. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2537. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2538. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2539. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2540. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2541. app.reSelectMenu.separatorHeight = 0.5;
  2542. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2543. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2544. app.reSelectMenu.textColor = [UIColor blackColor];
  2545. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2546. app.reSelectMenu.textShadowColor = nil;
  2547. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2548. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2549. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2550. app.reSelectMenu.highlightedSeparatorColor = nil;
  2551. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2552. app.reSelectMenu.highlightedTextShadowColor = nil;
  2553. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2554. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2555. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2556. app.reSelectMenu.subtitleTextShadowColor = nil;
  2557. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2558. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2559. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2560. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2561. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2562. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2563. app.reSelectMenu.borderWidth = 0.3;
  2564. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2565. app.reSelectMenu.closeAnimationDuration = 0.2;
  2566. app.reSelectMenu.animationDuration = 0.2;
  2567. app.reSelectMenu.bounce = NO;
  2568. [app.reSelectMenu setClosePreparationBlock:^{
  2569. // Backgroun reMenu (Gesture)
  2570. [_reMenuBackgroundView removeFromSuperview];
  2571. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2572. }];
  2573. }
  2574. - (void)toggleReSelectMenu
  2575. {
  2576. if (app.reSelectMenu.isOpen) {
  2577. [app.reSelectMenu close];
  2578. } else {
  2579. [self createReSelectMenu];
  2580. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2581. // Backgroun reMenu & (Gesture)
  2582. [self createReMenuBackgroundView:app.reSelectMenu];
  2583. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2584. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2585. }
  2586. }
  2587. #pragma --------------------------------------------------------------------------------------------
  2588. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2589. #pragma --------------------------------------------------------------------------------------------
  2590. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2591. {
  2592. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2593. UITableView *tableView = (UITableView*)self.view;
  2594. CGPoint touchPoint = [recognizer locationInView:self.view];
  2595. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2596. if ([self indexPathIsValid:indexPath])
  2597. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2598. else
  2599. _metadata = nil;
  2600. [self becomeFirstResponder];
  2601. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2602. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2603. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2604. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2605. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2606. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2607. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2608. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2609. [menuController setMenuVisible:YES animated:YES];
  2610. }
  2611. }
  2612. - (BOOL)canBecomeFirstResponder
  2613. {
  2614. return YES;
  2615. }
  2616. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2617. {
  2618. // For copy file, copy files, Open in ... :
  2619. //
  2620. // NO Directory
  2621. // NO Error Passcode
  2622. // NO In Session mode (download/upload)
  2623. // NO Template
  2624. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2625. if (_isSelectedMode == NO && _metadata && !_metadata.directory && [_metadata.session length] == 0) return YES;
  2626. else return NO;
  2627. }
  2628. if (@selector(copyFiles:) == action) {
  2629. if (_isSelectedMode) {
  2630. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2631. for (tableMetadata *metadata in selectedMetadatas) {
  2632. if (!metadata.directory && metadata.session.length == 0)
  2633. return YES;
  2634. }
  2635. }
  2636. return NO;
  2637. }
  2638. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2639. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2640. NSArray *items = [pasteboard items];
  2641. if ([items count] == 1) {
  2642. // Value : (NSData) fileID
  2643. NSDictionary *dic = [items objectAtIndex:0];
  2644. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2645. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2646. if (fileID) {
  2647. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2648. if (metadata) {
  2649. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2650. if (account) {
  2651. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2652. if (directoryUser)
  2653. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2654. return YES;
  2655. }
  2656. }
  2657. }
  2658. }
  2659. return NO;
  2660. }
  2661. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2662. BOOL isValid = NO;
  2663. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2664. NSArray *items = [pasteboard items];
  2665. if ([items count] <= 1) return NO;
  2666. for (NSDictionary *dic in items) {
  2667. // Value : (NSData) fileID
  2668. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2669. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2670. if (fileID) {
  2671. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2672. if (metadata) {
  2673. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2674. if (account) {
  2675. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2676. if (directoryUser) {
  2677. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2678. isValid = YES;
  2679. } else {
  2680. isValid = NO;
  2681. break;
  2682. }
  2683. } else {
  2684. isValid = NO;
  2685. break;
  2686. }
  2687. } else {
  2688. isValid = NO;
  2689. break;
  2690. }
  2691. } else {
  2692. isValid = NO;
  2693. break;
  2694. }
  2695. } else {
  2696. isValid = NO;
  2697. break;
  2698. }
  2699. }
  2700. return isValid;
  2701. }
  2702. return NO;
  2703. }
  2704. /************************************ COPY ************************************/
  2705. - (void)copyFile:(id)sender
  2706. {
  2707. // Remove all item
  2708. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2709. pasteboard.items = [[NSArray alloc] init];
  2710. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2711. [self copyFileToPasteboard:_metadata];
  2712. } else {
  2713. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2714. if (serverUrl)
  2715. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2716. }
  2717. }
  2718. - (void)copyFiles:(id)sender
  2719. {
  2720. // Remove all item
  2721. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2722. pasteboard.items = [[NSArray alloc] init];
  2723. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2724. for (tableMetadata *metadata in selectedMetadatas) {
  2725. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2726. [self copyFileToPasteboard:metadata];
  2727. } else {
  2728. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2729. if (serverUrl)
  2730. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2731. }
  2732. }
  2733. [self tableViewSelect:NO];
  2734. }
  2735. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2736. {
  2737. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2738. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2739. // Value : (NSData) fileID
  2740. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2741. [items addObject:item];
  2742. [pasteboard setItems:items];
  2743. }
  2744. /************************************ OPEN IN ... ******************************/
  2745. - (void)openinFile:(id)sender
  2746. {
  2747. [self openIn:_metadata];
  2748. }
  2749. /************************************ PASTE ************************************/
  2750. - (void)pasteFile:(id)sender
  2751. {
  2752. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2753. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2754. }
  2755. - (void)pasteFileEncrypted:(id)sender
  2756. {
  2757. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2758. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2759. }
  2760. - (void)pasteFiles:(id)sender
  2761. {
  2762. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2763. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2764. }
  2765. - (void)pasteFilesEncrypted:(id)sender
  2766. {
  2767. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2768. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2769. }
  2770. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2771. {
  2772. float timer = 0;
  2773. for (NSDictionary *dic in items) {
  2774. // Value : (NSData) fileID
  2775. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2776. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2777. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2778. if (metadata) {
  2779. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2780. if (account) {
  2781. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2782. if (directoryUser) {
  2783. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2784. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]];
  2785. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2786. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:_serverUrl session:k_upload_session taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  2787. });
  2788. timer += 0.1;
  2789. }
  2790. }
  2791. }
  2792. }
  2793. }
  2794. }
  2795. #pragma --------------------------------------------------------------------------------------------
  2796. #pragma mark ===== Lock Passcode =====
  2797. #pragma --------------------------------------------------------------------------------------------
  2798. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2799. {
  2800. return _failedAttempts;
  2801. }
  2802. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2803. {
  2804. return _lockUntilDate;
  2805. }
  2806. - (void)passcodeViewCloseButtonPressed:(id)sender
  2807. {
  2808. [self dismissViewControllerAnimated:YES completion:nil];
  2809. }
  2810. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2811. {
  2812. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2813. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2814. _lockUntilDate = nil;
  2815. _failedAttempts = 0;
  2816. aResultHandler(YES);
  2817. } else aResultHandler(NO);
  2818. } else aResultHandler(YES);
  2819. }
  2820. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2821. {
  2822. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2823. switch (aViewController.type) {
  2824. case BKPasscodeViewControllerCheckPasscodeType: {
  2825. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2826. // possiamo procedere alla prossima directory
  2827. [self performSegueDirectoryWithControlPasscode:false];
  2828. // avviamo la sessione Passcode Lock con now
  2829. app.sessionePasscodeLock = [NSDate date];
  2830. }
  2831. // disattivazione lock cartella
  2832. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2833. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2834. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2835. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2836. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2837. }
  2838. [self tableViewReloadData];
  2839. }
  2840. }
  2841. break;
  2842. default:
  2843. break;
  2844. }
  2845. }
  2846. - (void)comandoLockPassword
  2847. {
  2848. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2849. if (!serverUrl) return;
  2850. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2851. // se non è abilitato il Lock Passcode esci
  2852. if ([[CCUtility getBlockCode] length] == 0) {
  2853. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2854. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2855. [alertController addAction:okAction];
  2856. [self presentViewController:alertController animated:YES completion:nil];
  2857. return;
  2858. }
  2859. // se è richiesta la disattivazione si chiede la password
  2860. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2861. if (directory.lock) {
  2862. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2863. viewController.delegate = self;
  2864. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2865. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2866. viewController.inputViewTitlePassword = YES;
  2867. if ([CCUtility getSimplyBlockCode]) {
  2868. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2869. viewController.passcodeInputView.maximumLength = 6;
  2870. } else {
  2871. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2872. viewController.passcodeInputView.maximumLength = 64;
  2873. }
  2874. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2875. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2876. viewController.touchIDManager = touchIDManager;
  2877. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2878. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2879. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2880. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2881. [self presentViewController:navigationController animated:YES completion:nil];
  2882. return;
  2883. }
  2884. // ---------------- ACTIVATE PASSWORD
  2885. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2886. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2887. if ([self indexPathIsValid:indexPath])
  2888. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2889. } else {
  2890. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2891. }
  2892. }
  2893. #pragma mark -
  2894. #pragma --------------------------------------------------------------------------------------------
  2895. #pragma mark ===== Swipe Tablet -> menu =====
  2896. #pragma --------------------------------------------------------------------------------------------
  2897. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2898. {
  2899. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2900. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2901. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2902. return NO;
  2903. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  2904. return NO;
  2905. else
  2906. return YES;
  2907. }
  2908. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2909. {
  2910. }
  2911. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2912. {
  2913. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2914. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2915. if (direction == MGSwipeDirectionRightToLeft) {
  2916. // Delete
  2917. if (index == 0)
  2918. [self swipeDelete:indexPath];
  2919. // More
  2920. if (index == 1)
  2921. [self swipeMore:indexPath];
  2922. }
  2923. if (direction == MGSwipeDirectionLeftToRight) {
  2924. if (_metadata.favorite)
  2925. [self removeFavorite:_metadata];
  2926. else
  2927. [self addFavorite:_metadata];
  2928. }
  2929. return YES;
  2930. }
  2931. - (void)swipeDelete:(NSIndexPath *)indexPath
  2932. {
  2933. // Directory locked ?
  2934. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  2935. if (!lockServerUrl) return;
  2936. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2937. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) {
  2938. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2939. return;
  2940. }
  2941. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2942. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2943. [self performSelector:@selector(deleteFile) withObject:nil];
  2944. }]];
  2945. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2946. [alertController dismissViewControllerAnimated:YES completion:nil];
  2947. }]];
  2948. alertController.popoverPresentationController.sourceView = self.view;
  2949. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2950. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2951. [alertController.view layoutIfNeeded];
  2952. [self presentViewController:alertController animated:YES completion:nil];
  2953. }
  2954. - (void)swipeMore:(NSIndexPath *)indexPath
  2955. {
  2956. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2957. if (!serverUrl) return;
  2958. NSString *titoloCriptaDecripta, *titoloLock, *titleFavorite;
  2959. titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  2960. if (_metadata.favorite) {
  2961. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2962. } else {
  2963. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2964. }
  2965. if (_metadata.directory) {
  2966. // calcolo lockServerUrl
  2967. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2968. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  2969. if (directory.lock)
  2970. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2971. else
  2972. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2973. }
  2974. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  2975. // ******************************************* AHKActionSheet *******************************************
  2976. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2977. actionSheet.animationDuration = 0.2;
  2978. actionSheet.buttonHeight = 50.0;
  2979. actionSheet.cancelButtonHeight = 50.0f;
  2980. actionSheet.separatorHeight = 5.0f;
  2981. actionSheet.automaticallyTintButtonImages = @(NO);
  2982. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  2983. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2984. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2985. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  2986. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2987. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2988. // ******************************************* DIRECTORY *******************************************
  2989. if (_metadata.directory) {
  2990. BOOL lockDirectory = NO;
  2991. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2992. // Directory bloccata ?
  2993. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, dirServerUrl]];
  2994. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  2995. NSString *autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  2996. NSString *autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  2997. [actionSheet addButtonWithTitle: _metadata.fileName
  2998. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  2999. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3000. height: 50.0
  3001. type: AHKActionSheetButtonTypeDisabled
  3002. handler: nil
  3003. ];
  3004. if (!lockDirectory) {
  3005. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3006. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3007. backgroundColor:[UIColor whiteColor]
  3008. height: 50.0
  3009. type:AHKActionSheetButtonTypeDefault
  3010. handler:^(AHKActionSheet *as) {
  3011. [self openWindowShare:_metadata];
  3012. }];
  3013. }
  3014. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3015. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3016. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3017. backgroundColor:[UIColor whiteColor]
  3018. height: 50.0
  3019. type:AHKActionSheetButtonTypeDefault
  3020. handler:^(AHKActionSheet *as) {
  3021. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3022. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3023. textField.text = _metadata.fileName;
  3024. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  3025. //textField.delegate = self;
  3026. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3027. }];
  3028. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3029. NSLog(@"Cancel action");
  3030. }];
  3031. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3032. UITextField *fileName = alertController.textFields.firstObject;
  3033. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3034. }];
  3035. okAction.enabled = NO;
  3036. [alertController addAction:cancelAction];
  3037. [alertController addAction:okAction];
  3038. [self presentViewController:alertController animated:YES completion:nil];
  3039. }];
  3040. }
  3041. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory) {
  3042. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3043. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3044. backgroundColor:[UIColor whiteColor]
  3045. height: 50.0
  3046. type:AHKActionSheetButtonTypeDefault
  3047. handler:^(AHKActionSheet *as) {
  3048. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3049. }];
  3050. }
  3051. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  3052. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3053. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3054. backgroundColor:[UIColor whiteColor]
  3055. height: 50.0
  3056. type:AHKActionSheetButtonTypeDefault
  3057. handler:^(AHKActionSheet *as) {
  3058. // Settings new folder Automatatic upload
  3059. NSString *oldAutoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:app.activeUrl];
  3060. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  3061. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:app.activeUrl];
  3062. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:oldAutoUploadDirectory directoryID:nil];
  3063. if (app.activeAccount.length > 0 && app.activePhotos)
  3064. [app.activePhotos reloadDatasourceForced];
  3065. [self readFolder:serverUrl];
  3066. NSLog(@"[LOG] Update Folder Photo");
  3067. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:app.activeUrl];
  3068. if ([autoUploadPath length] > 0) {
  3069. [[CCSynchronize sharedSynchronize] readFileForFolder:_metadata.fileName serverUrl:serverUrl selector:selectorReadFileFolder];
  3070. }
  3071. }];
  3072. }
  3073. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES)) {
  3074. [actionSheet addButtonWithTitle:titoloLock
  3075. image:[UIImage imageNamed:@"actionSheetLock"]
  3076. backgroundColor:[UIColor whiteColor]
  3077. height: 50.0
  3078. type:AHKActionSheetButtonTypeEncrypted
  3079. handler:^(AHKActionSheet *as) {
  3080. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3081. }];
  3082. }
  3083. /*
  3084. if (!([_metadata.fileName isEqualToString:autoUploadFileName] == YES && [serverUrl isEqualToString:autoUploadDirectory] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3085. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3086. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3087. backgroundColor:[UIColor whiteColor]
  3088. height: 50.0
  3089. type:AHKActionSheetButtonTypeEncrypted
  3090. handler:^(AHKActionSheet *as) {
  3091. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3092. }];
  3093. }
  3094. */
  3095. [actionSheet show];
  3096. }
  3097. // ******************************************* FILE *******************************************
  3098. if (!_metadata.directory) {
  3099. UIImage *iconHeader;
  3100. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3101. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3102. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3103. else
  3104. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3105. [actionSheet addButtonWithTitle: _metadata.fileName
  3106. image: iconHeader
  3107. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3108. height: 50.0
  3109. type: AHKActionSheetButtonTypeDisabled
  3110. handler: nil
  3111. ];
  3112. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3113. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"]color:[NCBrandColor sharedInstance].brand]
  3114. backgroundColor:[UIColor whiteColor]
  3115. height: 50.0
  3116. type:AHKActionSheetButtonTypeDefault
  3117. handler:^(AHKActionSheet *as) {
  3118. [self openWindowShare:_metadata];
  3119. }];
  3120. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3121. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3122. backgroundColor:[UIColor whiteColor]
  3123. height: 50.0
  3124. type:AHKActionSheetButtonTypeDefault
  3125. handler:^(AHKActionSheet *as) {
  3126. [self performSelector:@selector(openIn:) withObject:_metadata];
  3127. }];
  3128. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3129. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3130. backgroundColor:[UIColor whiteColor]
  3131. height: 50.0
  3132. type:AHKActionSheetButtonTypeDefault
  3133. handler:^(AHKActionSheet *as) {
  3134. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3135. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3136. textField.text = _metadata.fileName;
  3137. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3138. }];
  3139. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3140. NSLog(@"Cancel action");
  3141. }];
  3142. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3143. UITextField *fileName = alertController.textFields.firstObject;
  3144. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3145. }];
  3146. okAction.enabled = NO;
  3147. [alertController addAction:cancelAction];
  3148. [alertController addAction:okAction];
  3149. [self presentViewController:alertController animated:YES completion:nil];
  3150. }];
  3151. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3152. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3153. backgroundColor:[UIColor whiteColor]
  3154. height: 50.0
  3155. type:AHKActionSheetButtonTypeDefault
  3156. handler:^(AHKActionSheet *as) {
  3157. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3158. }];
  3159. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3160. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3161. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3162. backgroundColor:[UIColor whiteColor]
  3163. height: 50.0
  3164. type:AHKActionSheetButtonTypeDefault
  3165. handler:^(AHKActionSheet *as) {
  3166. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3167. }];
  3168. }
  3169. /*
  3170. if (app.isCryptoCloudMode) {
  3171. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3172. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3173. backgroundColor:[UIColor whiteColor]
  3174. height: 50.0
  3175. type:AHKActionSheetButtonTypeEncrypted
  3176. handler:^(AHKActionSheet *as) {
  3177. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3178. }];
  3179. }
  3180. */
  3181. #ifdef DEBUG
  3182. /*
  3183. [actionSheet addButtonWithTitle:@"Hide file"
  3184. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"admin"] color:[NCBrandColor sharedInstance].brand]
  3185. backgroundColor:[UIColor whiteColor]
  3186. height: 50.0
  3187. type:AHKActionSheetButtonTypeDefault
  3188. handler:^(AHKActionSheet *as) {
  3189. [[NCManageDatabase sharedInstance] setMetadataStatusWithFileID:_metadata.fileID status:k_metadataStatusHide];
  3190. [self reloadDatasource];
  3191. }];
  3192. */
  3193. #endif
  3194. [actionSheet show];
  3195. }
  3196. }
  3197. #pragma --------------------------------------------------------------------------------------------
  3198. #pragma mark - ==== Datasource ====
  3199. #pragma --------------------------------------------------------------------------------------------
  3200. - (void)clearDateReadDataSource:(NSNotification *)notification
  3201. {
  3202. _dateReadDataSource = Nil;
  3203. [self reloadDatasource];
  3204. }
  3205. - (void)reloadDatasource
  3206. {
  3207. [self reloadDatasource:_serverUrl];
  3208. }
  3209. - (void)reloadDatasource:(NSString *)serverUrl
  3210. {
  3211. // test
  3212. if (app.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  3213. return;
  3214. // Search Mode
  3215. if(_isSearchMode) {
  3216. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3217. [self tableViewReloadData];
  3218. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3219. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3220. _noFilesSearchDescription = @"";
  3221. }
  3222. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3223. _noFilesSearchTitle = @"";
  3224. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3225. }
  3226. [self.tableView reloadEmptyDataSet];
  3227. return;
  3228. }
  3229. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3230. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3231. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3232. if (main) {
  3233. [main reloadDatasource];
  3234. } else {
  3235. [self tableViewReloadData];
  3236. [app.activeTransfers reloadDatasource];
  3237. }
  3238. return;
  3239. }
  3240. [app.activeTransfers reloadDatasource];
  3241. // Settaggio variabili per le ottimizzazioni
  3242. _directoryGroupBy = [CCUtility getGroupBySettings];
  3243. _directoryOrder = [CCUtility getOrderSettings];
  3244. // Controllo data lettura Data Source
  3245. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, serverUrl]];
  3246. NSDate *dateDateRecordDirectory = directory.dateReadDirectory;
  3247. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3248. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3249. _dateReadDataSource = [NSDate date];
  3250. // Data Source
  3251. NSString *sorted = _directoryOrder;
  3252. if ([sorted isEqualToString:@"fileName"])
  3253. sorted = @"fileName";
  3254. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  3255. if (directoryID) {
  3256. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND status = %i", app.activeAccount, directoryID, k_metadataStatusNormal] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3257. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3258. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy activeAccount:app.activeAccount];
  3259. }
  3260. } else {
  3261. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3262. }
  3263. [self tableViewReloadData];
  3264. }
  3265. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3266. {
  3267. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3268. if (selectedRows.count > 0) {
  3269. for (NSIndexPath *selectionIndex in selectedRows) {
  3270. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3271. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3272. [metadatas addObject:metadata];
  3273. }
  3274. }
  3275. return metadatas;
  3276. }
  3277. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3278. {
  3279. NSInteger section = indexPath.section + 1;
  3280. NSInteger row = indexPath.row + 1;
  3281. NSInteger totSections = [_sectionDataSource.sections count] ;
  3282. if ((totSections < section) || (section > totSections)) {
  3283. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3284. return nil;
  3285. }
  3286. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3287. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3288. if (fileIDs) {
  3289. NSInteger totRows =[fileIDs count] ;
  3290. if ((totRows < row) || (row > totRows)) {
  3291. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3292. return nil;
  3293. }
  3294. } else {
  3295. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3296. return nil;
  3297. }
  3298. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3299. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3300. return metadata;
  3301. }
  3302. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3303. {
  3304. NSInteger totSections =[_sectionDataSource.sections count] ;
  3305. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3306. return nil;
  3307. }
  3308. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3309. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3310. }
  3311. #pragma --------------------------------------------------------------------------------------------
  3312. #pragma mark - ==== Table ====
  3313. #pragma --------------------------------------------------------------------------------------------
  3314. - (void)tableViewSelect:(BOOL)edit
  3315. {
  3316. // chiudiamo eventuali swipe aperti
  3317. if (edit)
  3318. [self.tableView setEditing:NO animated:NO];
  3319. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3320. [self.tableView setEditing:edit animated:YES];
  3321. _isSelectedMode = edit;
  3322. if (edit)
  3323. [self setUINavigationBarSelected];
  3324. else
  3325. [self setUINavigationBarDefault];
  3326. [_selectedFileIDsMetadatas removeAllObjects];
  3327. [self setTitle];
  3328. }
  3329. - (void)tableViewReloadData
  3330. {
  3331. // store selected cells before relod
  3332. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3333. //store swipeOffset before relod
  3334. [_statusSwipeCell removeAllObjects];
  3335. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3336. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3337. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:indexPath];
  3338. }
  3339. // reload table view
  3340. [self.tableView reloadData];
  3341. // selected cells stored
  3342. for (NSIndexPath *path in indexPaths)
  3343. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3344. [self setTableViewFooter];
  3345. if (self.tableView.editing)
  3346. [self setTitle];
  3347. }
  3348. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3349. {
  3350. if (tableView.editing == 1) {
  3351. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3352. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3353. return NO;
  3354. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  3355. return NO;
  3356. else
  3357. return YES;
  3358. } else {
  3359. [_selectedFileIDsMetadatas removeAllObjects];
  3360. }
  3361. return YES;
  3362. }
  3363. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3364. {
  3365. return 60;
  3366. }
  3367. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3368. {
  3369. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3370. }
  3371. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3372. {
  3373. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3374. }
  3375. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3376. {
  3377. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3378. NSString *sectionTitle = [sections objectAtIndex:section];
  3379. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3380. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3381. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3382. return 20.f;
  3383. }
  3384. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3385. {
  3386. float shift;
  3387. UIVisualEffectView *visualEffectView;
  3388. NSString *titleSection;
  3389. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3390. return nil;
  3391. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3392. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3393. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3394. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3395. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3396. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3397. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3398. else titleSection = NSLocalizedString(titleSection,nil);
  3399. // Format title
  3400. NSString *currentDevice = [CCUtility currentDevice];
  3401. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3402. visualEffectView = [[UIVisualEffectView alloc] init];
  3403. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3404. } else {
  3405. UIVisualEffect *blurEffect;
  3406. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3407. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3408. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3409. }
  3410. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3411. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3412. shift = - 35;
  3413. else
  3414. shift = - 20;
  3415. } else shift = - 10;
  3416. // Title
  3417. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3418. titleLabel.backgroundColor = [UIColor clearColor];
  3419. titleLabel.textColor = [UIColor blackColor];
  3420. titleLabel.font = [UIFont systemFontOfSize:12];
  3421. titleLabel.textAlignment = NSTextAlignmentLeft;
  3422. titleLabel.text = titleSection;
  3423. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3424. [visualEffectView.contentView addSubview:titleLabel];
  3425. // Elements
  3426. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3427. elementLabel.backgroundColor = [UIColor clearColor];
  3428. elementLabel.textColor = [UIColor blackColor];;
  3429. elementLabel.font = [UIFont systemFontOfSize:12];
  3430. elementLabel.textAlignment = NSTextAlignmentRight;
  3431. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3432. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3433. NSUInteger rowsCount = [metadatas count];
  3434. if (rowsCount == 0) return nil;
  3435. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3436. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3437. [visualEffectView.contentView addSubview:elementLabel];
  3438. return visualEffectView;
  3439. }
  3440. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3441. {
  3442. return [_sectionDataSource.sections indexOfObject:title];
  3443. }
  3444. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3445. {
  3446. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3447. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3448. else
  3449. return nil;
  3450. }
  3451. /*
  3452. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3453. {
  3454. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3455. }
  3456. }
  3457. */
  3458. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3459. {
  3460. NSString *typeCell;
  3461. NSString *dataFile;
  3462. NSString *lunghezzaFile;
  3463. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3464. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3465. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3466. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3467. if (!serverUrl)
  3468. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3469. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3470. else typeCell = @"CellMainTransfer";
  3471. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3472. // variable base
  3473. cell.delegate = self;
  3474. cell.indexPath = indexPath;
  3475. // separator
  3476. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3477. // change color selection
  3478. UIView *selectionColor = [[UIView alloc] init];
  3479. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3480. cell.selectedBackgroundView = selectionColor;
  3481. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3482. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3483. // ----------------------------------------------------------------------------------------------------------
  3484. // DEFAULT
  3485. // ----------------------------------------------------------------------------------------------------------
  3486. cell.file.image = nil;
  3487. cell.status.image = nil;
  3488. cell.favorite.image = nil;
  3489. cell.shared.image = nil;
  3490. cell.local.image = nil;
  3491. cell.labelTitle.enabled = YES;
  3492. cell.labelTitle.text = @"";
  3493. cell.labelInfoFile.enabled = YES;
  3494. cell.labelInfoFile.text = @"";
  3495. cell.progressView.progress = 0.0;
  3496. cell.progressView.hidden = YES;
  3497. cell.cancelTaskButton.hidden = YES;
  3498. cell.reloadTaskButton.hidden = YES;
  3499. cell.stopTaskButton.hidden = YES;
  3500. cell.labelTitle.textColor = [UIColor blackColor];
  3501. // ----------------------------------------------------------------------------------------------------------
  3502. // File Name & Folder
  3503. // ----------------------------------------------------------------------------------------------------------
  3504. // nome del file
  3505. cell.labelTitle.text = metadata.fileName;
  3506. // è una directory
  3507. if (metadata.directory) {
  3508. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3509. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3510. lunghezzaFile = @" ";
  3511. // ----------------------------------------------------------------------------------------------------------
  3512. // Favorite Folder
  3513. // ----------------------------------------------------------------------------------------------------------
  3514. if (metadata.favorite) {
  3515. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3516. }
  3517. } else {
  3518. // File
  3519. dataFile = [CCUtility dateDiff:metadata.date];
  3520. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3521. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3522. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3523. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3524. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3525. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3526. cell.local.image = [UIImage imageNamed:@"local"];
  3527. else
  3528. cell.local.image = nil;
  3529. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3530. cell.accessoryType = UITableViewCellAccessoryNone;
  3531. }
  3532. // ----------------------------------------------------------------------------------------------------------
  3533. // File Image View
  3534. // ----------------------------------------------------------------------------------------------------------
  3535. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3536. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3537. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  3538. } else {
  3539. if (metadata.directory)
  3540. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3541. else
  3542. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3543. if (metadata.thumbnailExists)
  3544. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3545. }
  3546. // ----------------------------------------------------------------------------------------------------------
  3547. // Image Status cyptated & Lock Passcode
  3548. // ----------------------------------------------------------------------------------------------------------
  3549. // Directory con passcode lock attivato
  3550. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3551. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3552. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3553. cell.status.image = [UIImage imageNamed:@"passcode"];
  3554. // ----------------------------------------------------------------------------------------------------------
  3555. // Favorite
  3556. // ----------------------------------------------------------------------------------------------------------
  3557. if (metadata.favorite) {
  3558. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3559. }
  3560. // ----------------------------------------------------------------------------------------------------------
  3561. // Share
  3562. // ----------------------------------------------------------------------------------------------------------
  3563. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3564. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3565. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3566. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3567. // Aggiungiamo il Tap per le shared
  3568. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3569. // Shared with you
  3570. if (isShare) {
  3571. if (metadata.directory) {
  3572. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3573. cell.accessoryType = UITableViewCellAccessoryNone;
  3574. }
  3575. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3576. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3577. [tap setNumberOfTapsRequired:1];
  3578. cell.shared.userInteractionEnabled = YES;
  3579. [cell.shared addGestureRecognizer:tap];
  3580. }
  3581. // Mounted with you
  3582. if (isMounted) {
  3583. if (metadata.directory) {
  3584. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3585. cell.accessoryType = UITableViewCellAccessoryNone;
  3586. }
  3587. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3588. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3589. [tap setNumberOfTapsRequired:1];
  3590. cell.shared.userInteractionEnabled = YES;
  3591. [cell.shared addGestureRecognizer:tap];
  3592. }
  3593. // You share
  3594. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3595. if (metadata.directory) {
  3596. if ([shareLink length] > 0)
  3597. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3598. if ([shareUserAndGroup length] > 0)
  3599. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3600. cell.shared.userInteractionEnabled = NO;
  3601. } else {
  3602. if ([shareLink length] > 0)
  3603. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3604. if ([shareUserAndGroup length] > 0)
  3605. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3606. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3607. [tap setNumberOfTapsRequired:1];
  3608. cell.shared.userInteractionEnabled = YES;
  3609. [cell.shared addGestureRecognizer:tap];
  3610. }
  3611. }
  3612. } else {
  3613. cell.shared.userInteractionEnabled = NO;
  3614. }
  3615. // ----------------------------------------------------------------------------------------------------------
  3616. // downloadFile
  3617. // ----------------------------------------------------------------------------------------------------------
  3618. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3619. cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3620. // sessionTaskIdentifier : RELOAD + STOP
  3621. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3622. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3623. cell.cancelTaskButton.hidden = NO;
  3624. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3625. cell.reloadTaskButton.hidden = NO;
  3626. }
  3627. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3628. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3629. if (progress > 0) {
  3630. cell.progressView.progressTintColor = [UIColor blackColor];
  3631. cell.progressView.progress = progress;
  3632. cell.progressView.hidden = NO;
  3633. }
  3634. // ----------------------------------------------------------------------------------------------------------
  3635. // downloadFile Error
  3636. // ----------------------------------------------------------------------------------------------------------
  3637. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3638. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3639. if ([metadata.sessionError length] == 0)
  3640. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3641. else
  3642. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3643. }
  3644. }
  3645. // ----------------------------------------------------------------------------------------------------------
  3646. // uploadFile
  3647. // ----------------------------------------------------------------------------------------------------------
  3648. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3649. cell.status.image = [UIImage imageNamed:@"statusupload"];
  3650. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3651. cell.cancelTaskButton.hidden = NO;
  3652. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3653. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3654. cell.status.image = [UIImage imageNamed:@"statusstop"];
  3655. cell.reloadTaskButton.hidden = NO;
  3656. cell.stopTaskButton.hidden = YES;
  3657. } else {
  3658. [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3659. cell.stopTaskButton.hidden = NO;
  3660. cell.reloadTaskButton.hidden = YES;
  3661. }
  3662. // se non c'è una preview in bianconero metti l'immagine di default
  3663. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3664. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3665. cell.labelTitle.enabled = NO;
  3666. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3667. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3668. if (progress > 0) {
  3669. cell.progressView.progressTintColor = [UIColor blackColor];
  3670. cell.progressView.progress = progress;
  3671. cell.progressView.hidden = NO;
  3672. }
  3673. // ----------------------------------------------------------------------------------------------------------
  3674. // uploadFileError
  3675. // ----------------------------------------------------------------------------------------------------------
  3676. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3677. cell.labelTitle.enabled = NO;
  3678. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3679. if ([metadata.sessionError length] == 0)
  3680. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3681. else
  3682. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3683. }
  3684. }
  3685. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3686. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3687. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3688. // ======== MGSwipe ========
  3689. if (metadata.favorite)
  3690. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_unfavorite_", nil)] icon:[UIImage imageNamed:@"swipeUnfavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3691. else
  3692. cell.leftButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_favorite_", nil)] icon:[UIImage imageNamed:@"swipeFavorite"] backgroundColor:[UIColor colorWithRed:242.0/255.0 green:220.0/255.0 blue:132.0/255.0 alpha:1.000]]];
  3693. cell.leftExpansion.buttonIndex = 0;
  3694. cell.leftExpansion.fillOnTrigger = NO;
  3695. //centerIconOverText
  3696. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3697. [favoriteButton centerIconOverText];
  3698. //Right
  3699. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_delete_", nil)] icon:[UIImage imageNamed:@"swipeDelete"] backgroundColor:[UIColor redColor]], [MGSwipeButton buttonWithTitle:[NSString stringWithFormat:@" %@ ", NSLocalizedString(@"_more_", nil)] icon:[UIImage imageNamed:@"swipeMore"] backgroundColor:[UIColor lightGrayColor]]];
  3700. cell.rightSwipeSettings.transition = MGSwipeTransitionBorder;
  3701. //centerIconOverText
  3702. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3703. MGSwipeButton *moreButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:1];
  3704. [deleteButton centerIconOverText];
  3705. [moreButton centerIconOverText];
  3706. //restore swipeOffset after relod
  3707. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:indexPath] doubleValue];
  3708. if (swipeOffset < 0) {
  3709. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3710. [_statusSwipeCell removeObjectForKey:indexPath];
  3711. } else if (swipeOffset > 0) {
  3712. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3713. [_statusSwipeCell removeObjectForKey:indexPath];
  3714. }
  3715. return cell;
  3716. }
  3717. - (void)setTableViewFooter
  3718. {
  3719. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3720. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3721. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3722. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3723. UIFont *appFont = [UIFont systemFontOfSize:12];
  3724. footerLabel.font = appFont;
  3725. footerLabel.textColor = [UIColor grayColor];
  3726. footerLabel.backgroundColor = [UIColor clearColor];
  3727. footerLabel.textAlignment = NSTextAlignmentCenter;
  3728. NSString *folders;
  3729. NSString *files;
  3730. NSString *footerText;
  3731. if (_sectionDataSource.directories > 1) {
  3732. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3733. } else if (_sectionDataSource.directories == 1){
  3734. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3735. } else {
  3736. folders = @"";
  3737. }
  3738. if (_sectionDataSource.files > 1) {
  3739. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3740. } else if (_sectionDataSource.files == 1){
  3741. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3742. } else {
  3743. files = @"";
  3744. }
  3745. if ([folders isEqualToString:@""]) {
  3746. footerText = files;
  3747. } else if ([files isEqualToString:@""]) {
  3748. footerText = folders;
  3749. } else {
  3750. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3751. }
  3752. footerLabel.text = footerText;
  3753. [footerView addSubview:footerLabel];
  3754. [self.tableView setTableFooterView:footerView];
  3755. }
  3756. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3757. {
  3758. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3759. // settiamo il record file.
  3760. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3761. if (!_metadata)
  3762. return;
  3763. // se non può essere selezionata deseleziona
  3764. if ([cell isEditing] == NO)
  3765. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3766. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3767. if (self.tableView.editing) {
  3768. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3769. [self setTitle];
  3770. return;
  3771. }
  3772. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3773. if (!serverUrl) return;
  3774. // se è in corso una sessione
  3775. if ([_metadata.session length] > 0) return;
  3776. // file
  3777. if (_metadata.directory == NO) {
  3778. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3779. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3780. #ifdef DEBUG
  3781. // TEST ENCRYPTED/DECRYPTED
  3782. if ([_metadata.fileName containsString:@".dms"]) {
  3783. [[NCEndToEndEncryption sharedManager] decryptMetadata:_metadata activeUrl:app.directoryUser];
  3784. }
  3785. if ([_metadata.fileName containsString:@"test_encry_marino.jpg"]) {
  3786. [[NCEndToEndEncryption sharedManager] encryptMetadata:_metadata activeUrl:app.directoryUser];
  3787. }
  3788. #endif
  3789. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3790. } else {
  3791. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3792. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3793. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3794. }
  3795. }
  3796. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3797. }
  3798. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3799. {
  3800. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3801. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3802. [self setTitle];
  3803. }
  3804. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3805. {
  3806. if (!indexPath)
  3807. return NO;
  3808. NSInteger section = indexPath.section;
  3809. NSInteger row = indexPath.row;
  3810. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3811. if (section > lastSectionIndex || lastSectionIndex < 0)
  3812. return NO;
  3813. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3814. if (rowCount < 0)
  3815. return NO;
  3816. return row <= rowCount;
  3817. }
  3818. #pragma --------------------------------------------------------------------------------------------
  3819. #pragma mark ===== Navigation ====
  3820. #pragma --------------------------------------------------------------------------------------------
  3821. - (BOOL)shouldPerformSegue
  3822. {
  3823. // if background return
  3824. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3825. if (self.view.window == NO)
  3826. return NO;
  3827. // Collapsed ma siamo già in detail esci
  3828. if (self.splitViewController.isCollapsed)
  3829. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3830. return YES;
  3831. }
  3832. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3833. {
  3834. id viewController = segue.destinationViewController;
  3835. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3836. tableMetadata *metadata;
  3837. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3838. UINavigationController *nav = viewController;
  3839. _detailViewController = (CCDetail *)nav.topViewController;
  3840. } else {
  3841. _detailViewController = segue.destinationViewController;
  3842. }
  3843. if ([sender isKindOfClass:[tableMetadata class]]) {
  3844. metadata = sender;
  3845. [allRecordsDataSourceImagesVideos addObject:sender];
  3846. } else {
  3847. metadata = _metadata;
  3848. for (NSString *fileID in _sectionDataSource.allEtag) {
  3849. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3850. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3851. [allRecordsDataSourceImagesVideos addObject:metadata];
  3852. }
  3853. }
  3854. _detailViewController.metadataDetail = metadata;
  3855. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3856. _detailViewController.dateFilterQuery = nil;
  3857. [_detailViewController setTitle:metadata.fileName];
  3858. }
  3859. // can i go to next viewcontroller
  3860. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3861. {
  3862. NSString *nomeDir;
  3863. if(self.tableView.editing == NO) {
  3864. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3865. if (!serverUrl) return;
  3866. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3867. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", app.activeAccount, lockServerUrl]];
  3868. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  3869. if (directory.lock && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  3870. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3871. viewController.delegate = self;
  3872. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3873. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3874. viewController.inputViewTitlePassword = YES;
  3875. if ([CCUtility getSimplyBlockCode]) {
  3876. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3877. viewController.passcodeInputView.maximumLength = 6;
  3878. } else {
  3879. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3880. viewController.passcodeInputView.maximumLength = 64;
  3881. }
  3882. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3883. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3884. viewController.touchIDManager = touchIDManager;
  3885. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3886. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3887. //viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3888. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3889. [self presentViewController:navController animated:YES completion:nil];
  3890. return;
  3891. }
  3892. nomeDir = _metadata.fileName;
  3893. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3894. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  3895. if (!viewController) {
  3896. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  3897. viewController.serverUrl = serverUrlPush;
  3898. viewController.titleMain = _metadata.fileName;
  3899. viewController.textBackButton = _titleMain;
  3900. // save self
  3901. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  3902. [self.navigationController pushViewController:viewController animated:YES];
  3903. } else {
  3904. if (viewController.isViewLoaded) {
  3905. // Fix : Application tried to present modally an active controller
  3906. if ([self.navigationController isBeingPresented]) {
  3907. // being presented
  3908. } else if ([self.navigationController isMovingToParentViewController]) {
  3909. // being pushed
  3910. } else {
  3911. [self.navigationController pushViewController:viewController animated:YES];
  3912. }
  3913. }
  3914. }
  3915. }
  3916. }
  3917. @end