CCMain.m 228 KB

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